Interview Prep/Ansible/Inventory and Targeting

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.

All Ansible questions Roadmap: Ansible

More on Inventory and Targeting