---

- name: Launch new instance(s)
  amazon.aws.ec2:
    state: present
    aws_access_key: "{{ aws_access_key }}"
    aws_secret_key: "{{ aws_secret_key }}"
    region: "{{ aws_region }}"
    image: "{{ ec2_base_ami }}"
    instance_type: "{{ ec2_instance_type }}"
    count: "{{ ec2_instance_count }}"
    assign_public_ip: "{{ ec2_public_ip }}"
    group: "{{ ec2_security_group.name }}"
    key_name: "{{ ec2_keyname }}"
    wait: yes
  register: ec2

- name: Add newly created instance(s) to inventory
  ansible.builtin.add_host:
    hostname: "{{ item.public_dns_name }}"
    groupname: launched-instances
    ansible_user: admin
    ansible_ssh_common_args: "-o StrictHostKeyChecking=no"
  loop: "{{ ec2.instances }}"

- ansible.builtin.debug:
    msg: "Your newly created instance is reachable at: {{ item.public_dns_name }}"
  loop: "{{ ec2.instances }}"

- name: Wait for SSH to come up on all instances (give up after 2m)
  ansible.builtin.wait_for:
    state: started
    host: "{{ item.public_dns_name }}"
    port: 22
    timeout: 120
  loop: "{{ ec2.instances }}"
