I am having hard time figuring out idiomatic way of doing AWS infrastructure deployment and application e.g. EC2 instance provisioning in one go in same playbook. The problem being accessing EC2 host in the next play after AWS infrastructure creation. The example playbook is as follows:
I would tag the instances in your CF template, then reference those tagged hosts by the inventory groups that are created with the ec2.py dynamic inventory script. If you do this in two separate ansible-playbook runs, you won’t need to do anything special, the inventory will reflect the newly tagged instances. If you are doing this within the same play or playbook, you’ll need to update the inventory in memory, you can do that (in Ansible 2.0) with:
I stumbled across ec2.py dynamic inventory and immediately got bit the issue no refresh of dynamic inventory if executed from the same playbook. If I go with the approach of separating cloud infrastructure deployment and application provisioning into a separate playbooks then this problem can be avoided and I probably can stick with suggested approach of tagging resources in CF template.
I am just wondering how more experienced engineers approach this problem, what are the good practices?
Maybe you just need to add the host (cf.stack_outputs.PublicIP) to a group as per the example here using the add_host module, this will add it to your inventory temporarily
name: create some ec2 instances
ec2: …
register: ec2
name: Add new instance to host group
add_host: hostname={{ item.public_ip }} groupname=launched
with_items: ec2.instances
…
I’ve used something like this and then include the same roles I would call for a deployment on the host in the same playbook, just a different play.
hosts: launched
roles::
my_role
There are other examples on the ec2 page, it’s been update a lot since I last looked at it.
If you want to reuse the same playbooks tag your instances and just mention the tag and group name to later use the ec2.py inventory to manage the instance. (I’ve used a tag called AnsibleGroup)
hosts: launched:tag_AnsibleGroup_launched
launched would be a really esoteric group name to use, I’m just trying to fit in with your example.