ぶるーすくりーん

ぽんこつプログラマ日記

Ansibleをためしてみた

Ansibleをためしてみたメモです。

Ansible

Ansibleはchefやpuppetなど最近はやりの構成管理ツールのひとつ。

Ansibleはchefやpuppetと違い、リモートホストに特別な設定を行う必要がない。

構成もシンプル!

ステキ!

Ansible is Simple IT Automation

環境

Install

ホストマシンにAnsibleをインストール

~ % sudo apt-add-repository ppa:rquillo/ansible
~ % sudo apt-get update
~ % sudo apt-get install ansible
~ % ansible --version
ansible 1.6.2

ゲストOS作成

box作成

~ % mkdir -p vagrant/centos65
~ % cd !$
centos65 % vagrant box add centos65 https://github.com/2creatives/vagrant-centos/releases/download/v6.5.3/centos65-x86_64-20140116.box
centos65 % vagrant init centos65

Vagrantfileの以下の行を編集して、ゲストOSにIPを設定する

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network "public_network"
  config.vm.network "public_network", ip: "192.168.0.21"

Vagrant起動

centos65 % vagrant up
centos65 % vagrant ssh
[vagrant@vagrant-centos65 ~]$ ifconfig  # 設定したIPが反映されていることを確認
[vagrant@vagrant-centos65 ~]$ logout
Connection to 127.0.0.1 closed.

Ansibleの設定

ゲストOSにAnsibleからsshするための設定をしていきます。

Inventryfileの作成

centos65 % cat << EOF > hosts
[servers]
192.168.0.21

EOF

passwordなしでSSHするための設定

centos65 % ssh-agent bash
centos65 % ssh-add ~/.ssh/id_rsa

Ansible経由でゲストOSにping-pongしてみる

  • -m の後にはAnsibleのモジュール名を指定。
  • -i の後にはインベントリファイルと対象ホストのグループ名を指定。
centos65 % ansible -i hosts servers -m ping
192.168.0.21 | FAILED => SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the 33.10e

だがエラー (TдT)

centos65 % ping 192.168.0.21

通常のpingはとおる。

centos65 %  ansible -i hosts servers -m ping -vvvv

debug1: Trying private key: /home/mid/.ssh/id_dsa
debug3: no such identity: /home/mid/.ssh/id_dsa: No such file or directory
debug1: Trying private key: /home/mid/.ssh/id_ecdsa
debug3: no such identity: /home/mid/.ssh/id_ecdsa: No such fil33 or directory
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).

~/.ssh/の下の秘密鍵を使おうとして"Permission denied"になっている模様。

というわけでInventoryファイルにユーザとprivate_keyの設定を追加

centos65 % cat << EOF > hosts
[servers]
192.168.0.21 ansible_ssh_user=vagrant ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key

EOF

で、再トライ。結果をまつ。。

centos65 % ansible -i hosts servers -m ping
192.168.0.21 | success >> {
    "changed": false,
    "ping": "pong"
}

成功!

Ansibleコマンドをためす

以下のページを参考にAnsibleで環境構築を行っていきます。

-aで任意のコマンド指定ができる

centos65 % ansible -i hosts servers -a 'uname -r'
192.168.0.21 | success | rc=0 >>
2.6.32-431.3.1.el6.x86_64
centos65 % ansible -i hosts servers -a 'pwd'
192.168.0.21 | success | rc=0 >>
/home/vagrant

パッケージインストール

  • -myumモジュールを設定
  • -sでsudo実行
centos65 % ansible -i hosts servers -m yum -s -a name=telnet
192.168.0.21 | success >> {
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Loaded plugins: fastestmirror, versionlock\nLoading mirror speeds from cached hostfile\n * base: www.ftp.ne.jp\n * epel: kartolo.sby.datautama.net.id\n * extras: www.ftp.ne.jp\n * updates: www.ftp.ne.jp\nSetting up Install Process\nResolving Dependencies\n--> Running transaction check\n---> Package telnet.x86_64 1:0.17-47.el6_3.1 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch            Version                    Repository     Size\n================================================================================\nInstalling:\n telnet          x86_64          1:0.17-47.el6_3.1          base           58 k\n\nTransaction Summary\n================================================================================\nInstall       1 Package(s)\n\nTotal download size: 58 k\nInstalled size: 109 k\nDownloading Packages:\nRunning rpm_check_debug\nRunning Transaction Test\nTransaction Test Succeeded\nRunning Transaction\n\r  Installing : 1:telnet-0.17-47.el6_3.1.x86_64                              1/1 \n\r  Verifying  : 1:telnet-0.17-47.el6_3.1.x86_64                              1/1 \n\nInstalled:\n  telnet.x86_64 1:0.17-47.el6_3.1                                               \n\nComplete!\n"
    ]
}

モジュールのヘルプ表示

centos65 % ansible-doc yum

Playbookをためす

いよいよPlaybook。 YAML形式で記述していく。

simple-playbook.yml

  • hostsに対象ホストまたはグループを指定
  • tasksにタスクを記述していく。yum, serviceがモジュール名。
- hosts: servers
  sudo: yes
  tasks:
    - name: be sure httpd is installed
      yum: name=httpd state=latest

    - name: be sure httpd is running and enabled
      service: name=httpd state=started enabled=yes

playbook の syntax check

centos65 % ansible-playbook -i hosts simple-playbook.yml --syntax-check

playbook: simple-playbook.yml

playbook の task 一覧確認

centos65 % ansible-playbook -i hosts simple-playbook.yml --list-tasks

playbook: simple-playbook.yml

  play #1 (servers):
    be sure httpd is installed
    be sure httpd is running and enabled

dry-runで確認

centos65 % ansible-playbook -i hosts simple-playbook.yml --check
 ________________
< PLAY [servers] >
 ----------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


 _________________
< GATHERING FACTS >
 -----------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


ok: [192.168.0.21]
 __________________________________
< TASK: be sure httpd is installed >
 ----------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


changed: [192.168.0.21]
 ____________________________________________
< TASK: be sure httpd is running and enabled >
 --------------------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


failed: [192.168.0.21] => {"failed": true}
msg: cannot find 'service' binary or init script for service,  possible typo in service name?, aborting

FATAL: all hosts have already failed -- aborting
 ____________
< PLAY RECAP >
 ------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


           to retry, use: --limit @/home/mid/simple-playbook.retry

192.168.0.21               : ok=2    changed=1    unreachable=0    failed=1

cannot find 'service' binary or init script for service うーーん。

そもそもhttpdのインストールまだなんだし、当然な気する。

公式ドキュメント でも前の状態に依存するやつのには向いてないって書いてある。

Check mode is just a simulation, and if you have steps that use conditionals that depend on the results of prior commands, it may be less useful for you. However it is great for one-node-at-time basic configuration management use cases.

というわけでチャレンジ。

centos65 % ansible-playbook -i hosts simple-playbook.yml 
 ________________
< PLAY [servers] >
 ----------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


 _________________
< GATHERING FACTS >
 -----------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


ok: [192.168.0.21]
 __________________________________
< TASK: be sure httpd is installed >
 ----------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


changed: [192.168.0.21]
 ____________________________________________
< TASK: be sure httpd is running and enabled >
 --------------------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


changed: [192.168.0.21]
 ____________
< PLAY RECAP >
 ------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


192.168.0.21               : ok=3    changed=2    unreachable=0    failed=0   

centos65 % 

できたっぽいので確認。

[vagrant@vagrant-centos65 ~]$ sudo chkconfig --list httpd
httpd           0:off   1:off   2:on    3:on    4:on    5:on    6:off
[vagrant@vagrant-centos65 ~]$ sudo service httpd status
httpd (pid  8954) is running...

感想

ホスト側の環境準備が楽でよい。

YAML形式だから、Ansible とか python とかよくわかんない人でもPlaybookのメンテナンスはできそう。

    \   ^__^
     \  (oo)\_______
        (__)\       )\/\
            ||----w |
            ||     ||

次は、Vagrant の provisioning に Ansible 使うのためしてみたい。