Ansible and Dynamic Amazon EC2 Inventory Management

To create amazon ec2 instances dynamically and to manage them I have followed the following instructions-I have chosen Ubuntu 16.04 as my ansible controller machine and will be using an ubuntu AMI. I have also generated some credentials from amazon’s IAM. Add the credentials into environment variables.

export AWS_ACCESS_KEY_ID='YOUR_AWS_API_KEY'
export AWS_SECRET_ACCESS_KEY='YOUR_AWS_API_SECRET_KEY'

To get started with dynamic EC2 inventory management, we need to download 2 files. EC2.py and EC2.ini. I have used wget to get the files to my working directory.

wget https://raw.githubusercontent.com/ansible/ansible/devel/contrib/inventory/ec2.py
wget https://raw.githubusercontent.com/ansible/ansible/devel/contrib/inventory/ec2.ini

if you have installed ansible via pip you might need to create a directory in /etc directory called ansible. I installed ansible via pip so I had to create the directory. Move these to files to /etc/ansible/ directory. Please consider using sudo if required.


Please remember to download the ansible.cfg from ansible githubrepository and put it into same /etc/ansible/ directory.


So to use the dynamic inventory management script rather than the one provided with ansible (/etc/ansible/hosts), again we need to set a variable

export ANSIBLE_HOSTS=/etc/ansible/ec2.py

This tells the ansible in the control machine to look for ec2.py rather than hosts file. This ec2.py requires another configuration file called ec2.ini. You can put it in the same directory or you can define it manually at the top of ec2.py script by opening it in a text editor. (if required) add

export EC2_INI_PATH=/path/to/ec2.ini

Enjoy!