add newly created AWS EC2 IP to Ansible inventory at runtime

1.5k views Asked by At

I have a Ansible playbook "run-all.yml" like below:

---
- include: aws-ec2-create-instance.yml
- include: aws-ec2-install-software.yml

The first .yml will create EC2 instance, and the second .yml will install software for this newly created instance.

If I run each of these two playbook separately, it works fine.

My problem is, that I want to put these two together in one playbook "run-all.yml", so that I can run Ansible once to finish the whole process instead of two separate runs.

Then the IPs of the "aws-ec2-create-instance.yml" created EC2 instances, are not added to the Ansible inventory at runtime, then the"aws-ec2-install-software.yml" will be skipped due to no host found.

I'm trying to use the Ansible "add_host" module to add IPs to after instance creation, but it is somehow ugly. Is there a better way to add the EC2 instance IPs to inventory gracefully?

Thanks a lot.

1

There are 1 answers

3
keypoint On BEST ANSWER

It's doable and I achieved it by use module "add_host" which can dynamically add host to inventory where inventory is already loaded in memory, key is to make sure the groupname is correct.

- name: add new instance to host group at runtime
  add_host: hostname={{ ec2.instances[0].public_ip }} groupname=tag_{{ item.key }}_{{ item.value }}
  with_dict: dict