LoginSignup
7
2

More than 5 years have passed since last update.

Ansible で AWS EC2 にコマンドを発行してみる

Last updated at Posted at 2016-06-10

Ansible を使って AWS の EC2 にコマンドを発行してみます。

使用した Ansible のバージョンは 2.0.2.0 です。

この例では yum update を実行します。

まず、適当な場所にフォルダーを作り、cd しましょう。

$ mkdir ~/yumupdatetoec2
$ cd ~/yumupdatetoec2

次にプライベートキーを使用して SSH ログインができるように ssh_config を編集します。
ここではプライベートキーファイルが、~/.ssh/myprivatekey.pem にあるものとします。

~/yumupdatetoec2/ssh_config
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 の先頭行にあるものです。

~/yumupdatetoec2/inventory.ini
[mysection]
aws

Ansible が接続する SSH のコマンドライン引数を指定します。ここでは先ほど指定した ssh_config を指定しています。

~/yumupdatetoec2/ansible.cfg
[ssh_connection]
ssh_args = -F ssh_config

プレイブックを編集します。先頭行の mysection は inventory.ini にあるものです。

~/yumupdatetoec2/yumupdate.yml
- 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 
7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2