Ansible を使って AWS の EC2 にコマンドを発行してみます。
使用した Ansible のバージョンは 2.0.2.0 です。
この例では yum update を実行します。
まず、適当な場所にフォルダーを作り、cd しましょう。
$ mkdir ~/yumupdatetoec2
$ cd ~/yumupdatetoec2
次にプライベートキーを使用して SSH ログインができるように ssh_config を編集します。
ここではプライベートキーファイルが、~/.ssh/myprivatekey.pem にあるものとします。
Host aws
User ec2-user
HostName ec2-xxxxxxxxxxxx.amazonaws.com
IdentityFile ~/.ssh/myprivatekey.pem
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
次のコマンドを実行して設定が正しいかどうか調べてみます。正しければ EC2 にログインします。コマンド末尾の aws は ssh_config の先頭行にあるものです。
$ ssh -F ssh_config aws
Warning: Permanently added 'ec2-xxxxxxxxxxxx.amazonaws.com,xxx.xxx.xxx.xxx' (ECDSA) to the list of known hosts.
Last login: Fri Jun 10 10:42:34 2016 from xxx.xxx.xxx.xxx
__| __|_ )
_| ( / Amazon Linux AMI
___|\___|___|
https://aws.amazon.com/amazon-linux-ami/yyyy.mm-release-notes/
[ec2-user@ip-xxx-xxx-xxx-xxx ~]$
ログインができたことを確認したら exit しましょう。
[ec2-user@ip-xxx-xxx-xxx-xxx ~]$ exit
次にインベントリーファイルを作成します。インベントリーファイルは ansible が接続するホストを列挙するファイルです。ファイル中にある aws は ssh_config の先頭行にあるものです。
[mysection]
aws
Ansible が接続する SSH のコマンドライン引数を指定します。ここでは先ほど指定した ssh_config を指定しています。
[ssh_connection]
ssh_args = -F ssh_config
プレイブックを編集します。先頭行の mysection は inventory.ini にあるものです。
- hosts: mysection
tasks:
- name: Update Yum
yum: name=* state=latest
さぁコマンドを実行して yum update を実行しましょう。
$ ansible-playbook ./yumupdate.yml -i inventory.ini
実行結果が以下のように、ok のところが 1 以上で、changed、unreachabe、failed が 0 であれば成功です。
PLAY RECAP *********************************************************************
aws : ok=2 changed=0 unreachable=0 failed=0