Vagrant の provision を Ansible で行う
Vagrant の provision を Ansible で行う方法を紹介します。 Ansibleの使い方については、Ansibleをためしてみた を参照してください。
流れ
- Vagrantfile作成
ここにAnsibleでprovisioningを行うための設定を記述します。 - Inventoryfile作成
ここでAnsibleにどのグループにどのマシンをひもづけるかを教えてあげます。 - Playbook作成
ここでAnsibleにこんな処理をしてねって書きます。 - Box作成
Githubにここで説明するサンプルプロジェクトをコミットしてあるので、参考にしてみてください。
Vagrantfile作成
provisionにansible
を設定
config.vm.provision "ansible" do |ansible| ansible.limit = 'all' ansible.inventory_path = "hosts" ansible.playbook = "provisioning/playbook.yml" end
ansible.limit = 'all'
Vagrantfile
のマシン名とansible.inventory_path
で指定したInventoryfile内のましんめマシン名対応づけるためのおまじない。文字列、または配列で具体的なマシン名やグループ名を設定することもできるみたい。ansible.playbook
にPlaybookのパスを設定ansible.inventory_path
にInventryfileのパスを設定
network設定
AnsibleからゲストOSにつなぐ際に使用するので、IPアドレスを割り当てておく。
config.vm.network "public_network", ip: "192.168.0.21"
以上の設定を行って以下のようなVagrantfileを作成します。
Vagrantfile for provisioning by Ansible
Ansibleの設定
Inventoryfile作成
上記Vagrantfile
のansible.inventory_path
で指定したAnsibleのInventoryfileを作成しておきます。
centos65-hubot % cat << EOF > hosts [servers] 192.168.0.21 ansible_ssh_user=vagrant ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key EOF
上記例では、以下のような設定をしています。
servers
グループに192.168.0.21
のマシンを紐付け- AnsibleからSSHする際にユーザ
vagrant
を設定 - AnsibleからSSHする際にvagrant用の設定を使用するための設定
Playbook作成
上記Vagrantfile
のansible.playbook
で指定したAnsibleのPlaybookを作成しておきます。
centos65-hubot % mkdir provisioning centos65-hubot % cat << EOF > provisioning/playbook.yml - hosts: servers sudo: yes tasks: - name: be sure nodejs is installed yum: name=nodejs state=latest - name: be sure npm is installed yum: name=npm state=latest - name: be sure libevent-devel is installed yum: name=libevent-devel state=latest - name: be sure coffee-script is installed npm: global=yes name=coffee-script state=latest - name: be sure hubot is installed npm: global=yes name=hubot state=latest - name: be sure myhubot is created command: hubot --create myhubot EOF
上記例では、以下を実行するように定義してあります。
- Inventoryfile(
hosts
ファイル)で指定したservers
グループに対して処理を実行。 - sudoユーザで実行
- タスク一覧
yum
でnodejs
の最新をインストールyum
でnpm
の最新をインストールyum
でlibevent-devel
の最新をインストールnpm
でglobalにcoffee-script
の最新をインストールnpm
でglobalにhubot
の最新をインストールhubot --create myhubot
コマンドを実行してmyhubot
って名前のhubotくん作成
Box作成
準備ができたので、vagrantを起動してprovisioningを行ないます。
centos65-hubot % vagrant up
コーヒー飲みながらprovisioningの完了を待ちます。
完了したら、hubotが正しくインストールされているか確認します。
centos65-hubot % vagrant ssh [vagrant@vagrant-centos65 ~]$ ls myhubot [vagrant@vagrant-centos65 ~]$ cd myhubot [vagrant@vagrant-centos65 myhubot]$ sudo bin/hubot Hubot>
お疲れさまでした。