Access by ssh to an ec2 instance after creating it

Hi, I am creating an ec2 instance in AWS, but after creating it I need to log in via SSH and run some tasks on it.

The instance takes a few minutes to be ready, as I do not know how long it takes to be ready and nor the IP assigned by Amazon, my question as SSH login to a newly created instance without knowing its IP and its creation status?
Regards,

Hi there! That is more of an AWS question than an Ansible question. I might suggest posting the question on the AWS forums here:

https://repost.aws/

The community.aws.ec2_instance module returns facts about the ec2 including interfaces and IPs. Register these facts and you can access it.


- community.aws.ec2_instance:
aws_access_key: "{{ access_key }}"
aws_secret_key: "{{ secret_key }}"
security_token: "{{ session_token }}"
name: "{{ ec2_name }}"
key_name: "{{ ec2_key }}"
vpc_subnet_id: "{{ subnet_id }}"
security_group: "{{ secgroup_id }}"
network:
assign_public_ip: false
image_id: "{{ ami_image_id }}"
instance_type: "{{ ec2_size }}"
volumes: "{{ disk_list }}"
region: "{{ aws_region }}"
register: newec2

- set_fact:

ip_addr: newec2.instances[0].network_interfaces[0].private_ip_address

Adding to my earlier reply … we then use a wait_for task to wait for the EC2 to be ready for SSH.

- name: Wait for connection SSH port 22 to become open
wait_for:
port: 22
connect_timeout: 10
host: "{{ ip_addr }}"
search_regex: OpenSSH
# wait for 30 secs before starting to poll
delay: 30
# wait no more than 10 mins and fail
timeout: 600
sleep: 5
delegate_to: localhost
become: no

We use the ec2_instance module as well, but we use the build-in 'wait' parameter which works well:

https://docs.ansible.com/ansible/latest/collections/amazon/aws/ec2_instance_module.html#parameter-wait

Our wait step is in a different playbook downstream in a workflow. The upstream step in the workflow can create an EC2 or an ESX VM. We did it this way to be universally applicable. We have a workflow step to create a vm, a workflow step to create a DNS record for that VM, then a workflow step to customize that VM based on parameters coming into the workflow - apache, nginx, tomcat, mysql, etc. The create-vm step is a wrapper playbook that sources other playbooks based on IaaS platform (location) the user selected. We support ESX and AWS, but with this method could easily add Azure and Google and other cloud service providers or hypervisor platforms.

CREATE-VM.YML