入門 Ansible (1)
- 作者: 若山史郎
- 発売日: 2014/07/30
- メディア: Kindle版
- この商品を含むブログ (1件) を見る
準備
$ brew install ansible
$ ansible --version
ansible 1.7.1
- Python 2 系が必要(3系では動かず、今後の対応も不明だとか)
- 対象ホストでも Python 2 系がインストールされている必要があるとか
- /usr/bin/python を前提としているとのこと
- ansible_python_interpreter で python コマンドのパス指定可能
Vagrant で対象ホストを用意
$ vagrant box add hashicorp/precise64
$ vagrant init hashicorp/precise64
inventory ファイル
$ vagrant up
$ vagrant ssh-config --host sample01 >> ~/.ssh/config
$ cat <<\EOF > hosts
sample01
EOF
$ ansible -i hosts sample01 -m command -a 'date'
sample01 | success | rc=0 >>
Mon Aug 18 04:56:54 UTC 2014
$ ansible -i hosts all -m setup
sample01 | success >> {
"ansible_facts": {
"ansible_all_ipv4_addresses": [
"10.0.2.15"
],
...
"changed": false
}
グループ
[web]
web01.example.com
web02.example.com
[db]
db01.example.com
db02.example.com
グループのグループ
[hoge:children]
hogeweb
hogedb
[hogeweb]
web01.example.com
web02.example.com
[hogedb]
db01.example.com
db02.example.com
ホスト単位の設定
web01.example.com ansible_ssh_user=ec2-user
グループ単位の設定
[web]
web01.example.com
web02.example.com
[web:vars]
ansible_ssh_port=2222
ansible_python_interpreter=/usr/local/bin/python
playbook
ホストと inventory の準備
$ git diff Vagrantfile
diff --git a/Vagrantfile b/Vagrantfile
index 91b7b92..14c9e85 100644
--- a/Vagrantfile
+++ b/Vagrantfile
@@ -12,6 +12,9 @@ Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# Every Vagrant virtual environment requires a box to build off of.
config.vm.box = "hashicorp/precise64"
+ config.vm.define :web01
+ config.vm.define :web02
+
# Disable automatic box update checking. If you disable this, then
# boxes will only be checked for updates when the user runs
# `vagrant box outdated`. This is not recommended.
$ vagrant up
$ vagrant ssh-config >> ~/.ssh/config
$ cat <<\EOF > hosts
[web]
web01
web02
EOF
playbook を書いてみる
$ cat <<\EOF > web.yml
---
- hosts: all
sudo: yes
remote_user: vagrant
vars:
username: newuser
tasks:
- name: ユーザーを追加
user: name={{ username }} group=admin shell=/bin/bash
EOF
$ ansible-playbook -i hosts web.yml
PLAY [all] ********************************************************************
GATHERING FACTS ***************************************************************
ok: [web02]
ok: [web01]
TASK: [ユーザーを追加] ***************************************************************
changed: [web01]
changed: [web02]
PLAY RECAP ********************************************************************
web01 : ok=2 changed=1 unreachable=0 failed=0
web02 : ok=2 changed=1 unreachable=0 failed=0
handler, notify
タスクの notify で handlers で定義した名前を指定すると、そのハンドラを実行出来る感じ。
tasks:
- name: 設定ファイルをコピー
copy: src=httpd.conf dest=/etc/httpd/conf/httpd.conf
notify: apacheの再起動
handlers:
- name: apacheの再起動
service: name=httpd sate=restarted