How to Setup Ansible AWS Dynamic Inventory

When you are using Ansible with AWS, it will be a hectic task to maintain the inventory file as AWS has frequently changing IP’s, autoscaling instances and much more. However, there is an easy solution called ansible dynamic inventory. It is basically a python script which makes an API call to get the instance information when you run the ansible commands. This will give you dynamic inventory details to manage the AWS infrastructure.

Setup Ansible AWS Dynamic Inventory

In this tutorial, you will learn how to setup a dynamic inventory for AWS using boto and the python script.

Follow the steps carefully for the setup.

1. Install the boto library using pip. If you don’t have pip installed, you can follow this document to install it –> Install python pip

2. Download the Inventory Script to /etc/ansible directory.

3. Make the file executable.

4. Download the ec2.ini file to /etc/ansible directory.

5. The ec2.ini file has the default AWS configurations which are read by file. So comment out and configure the necessary parameter to avoid long query times. Once such example is the “regions” parameter. By default, the value is “all”. This makes API calls to all the regions. So it is better to mention only the specific aws region that you use.

Under the [credentials] section you need to mention the aws access key and private key to for the boto library to make the API call.

READ  How To Install and Configure GUI for Amazon EC2 RHEL 7 Instance

Alternatively, you can create a credentials file in your home as shown below.

Open the credentials file and make the entries as shown below.

Note: If you are using AWS instance for this setup and have an IAM role with permissions to access AWS services, you don’t need to add the access key and secret key to the credentials file.

6. Now test the inventory configure using the following command.

You should get the output as shown below.

If you have some instances up and running, you will get the output with all the instance details.

7. If you want to use the dynamic inventory as a default ansible inventory, you need to edit the ansible.cfg file present in /etc/ansible directory and search for inventory parameter in the ansible.cfg. Change the inventory parameter value as shown below.

Now you can run the normal ansible commands against the dynamic inventory. For example, the following command will run a ping command against all the running ec2 instances fetched using the dynamic inventory.


From this tutorial, you have learned how to setup the Ansible AWS dynamic inventory. Now, you can use the Ansible AWS modules to create VPC, ec2 instances and much more. Leave a comment for queries.

Free DevOps Resources

Get DevOps news, tutorials and resources in your inbox. A perfect way If you want to get started with devops. Like you, we dont like spam.