ansible and reloading AWS dynamic inventory
I'd probably use the EC2 dynamic inventory script instead, which you can employ by configuring ec2.ini
and passing -i ec2.py
to ansible-playbook
.
See http://docs.ansible.com/ansible/intro_dynamic_inventory.html#example-aws-ec2-external-inventory-script for more info.
Note that there are plenty of options in ec2.ini
. Be sure to have a look at those, e.g. cache_max_age
. You can also make the inventory generation faster by filtering unnecessary resources (e.g. set rds = False
if you are only interested in EC2 instances).
UPDATE: With Ansible 2.x+ you can also use - meta: refresh_inventory
mid-play.
While the meta: refresh_inventory
is the "preferred method", I tend to like OP's proposal of using ec2_remote_facts
in conjunction with add_host
. I've setup such a playbook and it has the strength to be 100% dynamic without caching glitches.
Assuming your ASG fired up instances with the env: cool_asg_instance
tag, just add the following under the ec2_asg
playbook call:
- ec2_remote_facts: filters: "tag:env": "cool_asg_instance" register: instance_facts
You'll then gather a full JSON dataset containing all the needed informations, from there you can use Jinja2
capabilities within the playbook to extract newly created IP addresses, i.e.:
- name: group hosts add_host: hostname={{ item }} groups=launched with_items: "{{ instance_facts.instances|selectattr('state', 'equalto', 'running')|map(attribute='private_ip_address')|list }}"
Filter is courtesy of this wonerfull blog post: https://bonovoxly.github.io/2016-02-11-ansible-stuffs-ec2_remote_facts_instead_of_ec2_py
From now on you can use the launched
group on your parent deployment YAML file like this:
- hosts: launched gather_facts: no tasks: - name: wait for SSH wait_for: port=22 host="{{ inventory_hostname }}" search_regex=OpenSSH delay=5
Some may ask why the headache, well imagine that instead of having an hideous userdata
which will git clone
both Ansible and a playbook from the Internet, you can trigger the instance setup from your own deployment center by setting up a simple SNS topic which will publish to a SQS queue, watched by a 10 lines python code (https://github.com/alexandregama/python-sqs-consumer/blob/master/sqs-message-consumer-polling.py) which will trigger Ansible when a new instance comes out.