Ansible AWS Lookup Plugins

Once we started linking multiple CloudFormation stacks together with Ansible we started to feel the need to query Amazon Web Services for both the output values from existing CloudFormation stacks and certain other values, such as security group IDs and Elasticache Replication Group Endpoints. We found that the quickest and easiest way to gather this information was with a handful of Ansible Lookup Plugins.

I’ve put the code for the more generic Ansible AWS Lookup Plugins on github and even if you’re an Ansible user who’s not using AWS they are worth a look just to see how easy it is to write one.

In order to use these lookup plugins you’ll want to configure both your default AWS credentials and, unless you want to keep the plugins alongside your playbooks, your lookup plugins path in your Ansible config.

First we configure the credentials for boto, the underlying AWS library used by Ansible.

cat ~/.aws/credentials
[default]
aws_access_key_id = 
aws_secret_access_key =

Then we can tell ansible where to find the plugins themselves.

cat ~/.ansible.cfg

[defaults]
...
lookup_plugins = /path/to/git/checkout/cloudformations/ansible-plugins/lookup_plugins

And lastly we can test that everything is working correctly

$ cat region-test.playbook 
---
- hosts: localhost
  connection: local
  gather_facts: False

  tasks:
  - shell: echo region is =={{ item }}==
    with_items: lookup('aws_regions').split(',')

# and then run the playbook
$ ansible-playbook -i hosts region-test.playbook

Now you’ve seen how easy it is, go write your own!