You need to add a newly provisioned EC2 instance to the inventory in the same playbook that creates it.
IntermediateScenarioInventory and Targeting
Answer
Situation read → The host does not exist at inventory-parse time.
What I'd do → Create it, wait for SSH, then add_host.
- hosts: localhost
tasks:
- amazon.aws.ec2_instance: { name: app1, image_id: ami-0abc, instance_type: t3.micro, wait: true }
register: ec2
- ansible.builtin.add_host:
name: "{{ ec2.instances[0].private_ip_address }}"
groups: new_app
- ansible.builtin.wait_for:
host: "{{ ec2.instances[0].private_ip_address }}"
port: 22
timeout: 300
- hosts: new_app
tasks:
- ansible.builtin.ping:
Why → add_host mutates the in-memory inventory, and a later play can target the new group.
Interview tip → Alternatively call meta: refresh_inventory when using a dynamic inventory plugin.
More on Inventory and Targeting
You are handed a fresh Ansible project and 10 servers. How do you make sure Ansible can reach all of them before writing any playbook?BeginnerYour team keeps prod and staging hosts in one inventory file and someone ran a playbook on prod by mistake. How do you prevent it?IntermediateYou need to run a playbook on only the web servers in Mumbai that are not in the canary group. How?BeginnerServers are autoscaled in AWS and IPs change daily. How do you keep the inventory accurate?IntermediateA host is reachable by SSH on port 2222 with a different user from all others. How do you model that?BeginnerYou must configure servers in a private subnet that is only reachable through a bastion.Intermediate