Aws and Ansible Dynamic Inventory

One of the things my multiple environment Ansible layout uses, is an AWS dynamic inventory.

The last thing I want to discuss is how to properly secure and configure the dynamic inventory script between Ansible and AWS.

Step 1: Create new read-only IAM Credentials

The first thing we want to do is to create new AWS IAM credentials limited to just what the dynamic inventory needs.

We do so, by logging into the AWS console with our "Admin" user. And navigating to the IAM service, and clicking the "Policies" link in the left-hand navigation. Click the "Create Policy" button. create policy

On the "Create Policy" page, click the JSON tab. json tab

Replace the contents of this editor pane with the following policy I modified from here.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AnsibleInventory",
            "Effect": "Allow",
            "Action": [
                "ec2:Describe*",
                "route53:ListHostedZones",
                "route53:ListResourceRecordSets",
                "rds:Describe*",
                "elasticache:Describe*"
            ],
            "Resource": "*"
        }
    ]
}

Click "Review Policy".

Add a "Name" and "Description", then click "Create Policy". review policy

Create a new group which is assigned this newly created policy.

new group 1
new group 2
new group 3

Create a new user assigned to the newly created group. This user needs only programmatic access (no console). Don’t forget to save the key_id and secret key.

new user 1
new user 2
new user 3
new user 4
new user 5

Step 2 Install and Configure Needed AWS Libraries

The ec2.py script requires the following Python libraries:

  • boto

  • botocore

  • awscli

I usually install these using pip:

pip install boto botocore awscli

The next step is to configure the boto profile for your environment:

[user@host ~]# aws --profile integration-inventory configure
AWS Access Key ID [None]: AKIA3P46BU3KR2F7O47M
AWS Secret Access Key [None]: SDFADSLKJW/SDAF;LKDJSFA<ENTER>
Default region name [None]: <ENTER>
Default output format [None]: <ENTER>

Tie this boto profile to your AWS dynamic inventory by editing the ec2.ini file in your inventory folder and modifying the line:

boto_profile = integration-inventory

Now you don’t have to mess with AWS credentials when you run Ansible commands.

And the account you’re using for dynamic inventory doesn’t have access to make changes to your AWS account.