カタカタブログ

SIerで働くITエンジニアがカタカタした記録を残す技術ブログ。Java, Oracle Database, Linuxが中心です。たまに数学やデータ分析なども。

Ansible Localを使ってVagrant仮想マシンをプロビジョニングしてみた

はじめに

Vagrantで作った仮想マシンをプロビジョニングする方法として、ansible-localというプロビジョナーがあるのでそれを使ってみた。
https://www.vagrantup.com/docs/provisioning/ansible_local.html
この方法だとゲストOSにansibleがインストールされ、ホストから連携されたPlaybookを実行できるので、ホストOSにansibleをインストールする必要がなく便利。

今回の環境情報は以下の通り。

  • ホストOS: Windows 10
  • VirtualBox: 5.2.8
  • Vagrant: 2.0.3
  • ゲストOS: CentOS 7.4
  • Ansible: 2.4.2

ゲスト仮想マシン作成

まずホストOSでゲスト仮想マシンを構築する作業を行う。
ansibleのPlaybookはホスト側とゲスト側の共有フォルダに配置できると便利なので、Vagrant仮想マシンにGuest Additionsをインストールする必要がある。
vagrant-vbguestプラグインを入れておくと、Guest Additionsが自動でインストールされるのでこれを導入しておく。

>vagrant plugin install vagrant-vbguest

仮想OSは最新のCentOS 7とするため、boxを追加する。

>vagrant box add centos/7
==> box: Loading metadata for box 'centos/7'
  box: URL: https://vagrantcloud.com/centos/7
This box can work with multiple providers! The providers that it
can work with are listed below. Please review the list and choose
the provider you will be working with.

1) hyperv
2) libvirt
3) virtualbox
4) vmware_desktop

Enter your choice: 3
==> box: Adding box 'centos/7' (v1803.01) for provider: virtualbox
  box: Downloading: https://vagrantcloud.com/centos/boxes/7/versions/1803.01/providers/virtualbox.box
  box: Download redirected to host: cloud.centos.orgining: --:--:--)
  box: Progress: 100% (Rate: 515k/s, Estimated time remaining: --:--:--)
==> box: Successfully added box 'centos/7' (v1803.01) for 'virtualbox'!

> vagrant box list
centos/7 (virtualbox, 1803.01)

仮想マシン用フォルダを用意し、そこで仮想マシンを作成する(※今回はdev-centos7というフォルダを用意)。

dev-centos7>vagrant init centos/7
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.

仮想マシンができたので起動する。

dev-centos7>vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos/7'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'centos/7' is up to date...
==> default: Setting the name of the VM: dev-centos7_default_1523939184079_33788
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
  default: Adapter 1: nat
==> default: Forwarding ports...
  default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
  default: SSH address: 127.0.0.1:2222
  default: SSH username: vagrant
  default: SSH auth method: private key
  default:
  default: Vagrant insecure key detected. Vagrant will automatically replace
  default: this with a newly generated keypair for better security.
  default:
  default: Inserting generated public key within guest...
  default: Removing insecure key from the guest if it's present...
  default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
  default: No guest additions were detected on the base box for this VM! Guest
  default: additions are required for forwarded ports, shared folders, host only
  default: networking, and more. If SSH fails on this machine, please install
  default: the guest additions and repackage the box to continue.
  default:
  default: This is not an error message; everything may continue to work properly,
  default: in which case you may ignore this message.
==> default: Rsyncing folder: /cygdrive/c/vms/dev-centos7/ => /vagrant

仮想マシンにsshログインする。

dev-centos7>vagrant ssh
[vagrant@localhost ~]$ cat /etc/redhat-release
CentOS Linux release 7.4.1708 (Core)

正常に起動、接続できた!

ansible-localでプロビジョニング

プロビジョニングとして、今回は簡単なApacheをインストール・起動するためのAnsible Playbookを用意し、
それをvagrantからの命令のみでゲストOS内で実行し、環境を構築することを行う。

ゲストOSをいったん停止し、Vagrantfileを以下のように修正する。

Vagrant.configure("2") do |config|
 config.vm.box = "centos/7"
 config.vm.network "public_network"
 config.vm.network "private_network", ip: "192.168.33.10"

 config.vm.synced_folder "./ansible", "/ansible"
 config.vm.provision "ansible_local" do |ansible|
  ansible.playbook = "/ansible/web.yml"
 end
end

config.vm.synced_folderはホストOSのansibleフォルダをゲストOSの/ansibleパスにフォルダ同期するための設定で、
これを行うには事前にGuest Additionsがインストールされている必要があるが、今回はvagrant-vbguestプラグインによって導入済みの状態となっている。
config.vm.provision "ansible_local"設定により、Vagrantからプロビジョニングに使うansibleのPlaybookファイルを指定する。

Playbook等のymlファイルは、Vagrantの仮想マシン用フォルダにansibleフォルダを作成し、Playbook等のファイルを配置しておく。
これが上の設定でゲストOSに同期され、見えるようになっていることがポイント。

ホストOSの仮想マシン用フォルダ構成

dev-centos7
└─ansible
  │ web.yml
  │
  └─roles
    └─httpd
      └─tasks
          main.yml

Playbookは以下を用意
web.yml

- hosts: all
 sudo: yes
 roles:
  - httpd

roles/httpd/tasks/main.yml

- name: install apache
 yum:
  name: httpd
  state: latest
- name: start apache
 service:
  name: httpd
  state: started
  enabled: yes

これで準備はOK。
ゲストOSを起動し、ホスト側でプロビジョニングコマンドを実行する。

> vagrant provision
==> default: Running provisioner: ansible_local...
Vagrant has automatically selected the compatibility mode '2.0'
according to the Ansible version installed (2.4.2.0).

Alternatively, the compatibility mode can be specified in your Vagrantfile:
https://www.vagrantup.com/docs/provisioning/ansible_common.html#compatibility_mode
  default: Running ansible-playbook...
[DEPRECATION WARNING]: Instead of sudo/sudo_user, use become/become_user and
make sure become_method is 'sudo' (default). This feature will be removed in
version 2.6. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.

PLAY [all] *********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [default]

TASK [httpd : install apache] **************************************************
changed: [default]

TASK [httpd : start apache] ****************************************************
changed: [default]

PLAY RECAP *********************************************************************
default          : ok=3  changed=2  unreachable=0  failed=0

ansible Playbookの実行ログが表示され、成功していることを確認!

最後にプロビジョニングが想定通りを確認するため、ゲストOSにsshログインする。

[vagrant@localhost ~]$ systemctl status httpd
● httpd.service - The Apache HTTP Server
 Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
 Active: active (running) since Wed 2018-04-18 03:21:02 UTC; 12s ago
  Docs: man:httpd(8)
     man:apachectl(8)
Main PID: 19819 (httpd)
 Status: "Total requests: 0; Current requests/sec: 0; Current traffic: 0 B/sec"
 CGroup: /system.slice/httpd.service
     tq19819 /usr/sbin/httpd -DFOREGROUND
     tq19820 /usr/sbin/httpd -DFOREGROUND
     tq19821 /usr/sbin/httpd -DFOREGROUND
     tq19822 /usr/sbin/httpd -DFOREGROUND
     tq19823 /usr/sbin/httpd -DFOREGROUND
     mq19824 /usr/sbin/httpd -DFOREGROUND

apacheがインストールされ起動していることを確認!
また、ホストOSからゲストOSにhttpで接続し、Apacheの画面が見れることも確認した。
f:id:osn_th:20180418131042p:plain

まとめ

Vagrantで作成した仮想マシンをansible-localでプロビジョニングするための方法を確認した。
ホスト側でansible Playbookを用意しておくだけで自動的にゲストOS内でansibleのインストールとPlaybook実行がvagrantから実行できるので、
非常に簡単に仮想マシンのプロビジョニングができた。
これで仮想マシン上の環境構築はansibleモジュール等で簡単に構築できるようになるので、DBや他のミドルウェア検証等も手軽にできそう。

以上!