LoginSignup
64
57

More than 5 years have passed since last update.

AnsibleのDynamic InventoryでAWS EC2管理

Last updated at Posted at 2015-03-30

やりたいこと

AnsibleのInventoryをファイルではなく、EC2インスタンスに付けたタグで管理したい

背景

  • AWS Auto Scaling を使うとIPアドレスが動的にインスタンスに割り当てられるため、Inventoryファイルもその都度、メンテナンスしないといけないのだが、やりたくない
  • AnsibleのDynamic Inventory: http://docs.ansible.com/intro_dynamic_inventory.html

手順

  1. EC2インスタンスにenvとroleタグ(タグ名は何でも構わない)を付けておく
    予め、AutoScalingGroupにタグを設定しておくと便利(Tag New InstancesをYesに設定)
    asg.png

  2. 本番(production)とステージング(stage)のDynamic Inventory作成

  • Inventory directoryはこんな感じ
hosts/
├── production
│   ├── ec2.ini
│   ├── ec2.py
│   └── group_vars
│       └── tag_role_webserver
└── stage
    ├── ec2.ini
    ├── ec2.py
    └── group_vars
        └── tag_role_webserver
  • ansibleに付属している下記の二つのファイルをInventoryディレクトリにコピーして使う
 $ANSIBLE_HOME/ansible/plugins/inventory/ec2.py
 $ANSIBLE_HOME/ansible/plugins/inventory/ec2.ini
  • ec2.ini はどのインスタンスを対象にするかをいろいろ設定できる。
  • 例えば、東京リージョンで、envタグがstageのインスタンスを対象にする場合
ec2.ini
regions = ap-northeast-1
instance_filters = tag:env=stage
  • instance_filtersはカンマ区切りで複数設定できるが、OR条件となる
  • 今のところ、AND条件設定はできない
  • private ip address を取得したい場合
ec2.ini
vpc_destination_variable = private_ip_address
  • Cacheしたくない場合は
ec2.ini
cache_max_age = 0
  • group_vars/tag_<タグ名>_<タグ値> というファイル名でVariableを設定可能(タグと関連付けられている)

コマンド

  • 対象インスタンス一覧
./hosts/stage/ec2.py --list
  • 詳細情報取得
./hosts/stage/ec2.py --host 10.0.5.5
  • ステージング環境の全インスタンスにdateコマンドを実行する例
ansible -i hosts/stage all -a "date"
  • ステージング環境の10.0.5.5サーバにwebserverのplaybookのnginxタグを実行する
ansible-playbook -i stage webserver.yml -l 10.0.5.5 -t nginx
  • playbookはこんな感じ
---
- hosts: tag_role_webserver
  remote_user: root
  roles:
    - { role: nginx, tags: [ "nginx"] }
  • hosts: tag_<タグ名>_<タブ値> 形式

結論

  • AWS Auto Scalingを使って自動的にインスタンス数を増やしたりする場合はとても便利
  • AWS Auto Scalingではインスタンスが古いAMIからlaunchされる課題があるが、Auto Scaling ライフサイクルフックと組み合わせてInService状態になる前にansbleを実行することで最新状態にすることができる
64
57
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
64
57