# Reliable way to detect when EC2 instance is ready for login

**URL:** <https://forum.ansible.com/t/reliable-way-to-detect-when-ec2-instance-is-ready-for-login/21736>\
**Category:** Ansible Project\
**Created:** [June 10, 2016, 4:40pm UTC](https://forum.ansible.com/t/reliable-way-to-detect-when-ec2-instance-is-ready-for-login/21736 "2016-06-10T16:40:25Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Michael\_Spiegle](https://avatars.discourse-cdn.com/v4/letter/m/8797f3/32.png) [@Michael\_Spiegle](https://forum.ansible.com/u/Michael_Spiegle)\
**Post date:** [June 10, 2016, 4:40pm UTC](https://forum.ansible.com/t/reliable-way-to-detect-when-ec2-instance-is-ready-for-login/21736/1 "2016-06-10T16:40:25Z")

</div>

When I provision an EC2 instance, I add a user\_data script which drops an SSH pubkey so I can login as root. The problem is that it’s difficult to tell exactly when cloud-init has been completed. Even if port 22 is accepting connections, the pubkey may not be ready yet and thus SSH logins will fail. I use the following task to try to determine when the instance will accept my connection:

`

- name: ensure instance is ready

become: no

raw: printf “success”

register: result

until: ‘“success” in result.stdout\_lines’

retries: 300

delay: 1

failed\_when: false

`

This task works maybe 75% of the time. A small fraction of the time, I get a FATAL UNREACHABLE error, but if I rerun the playbook immediately after, it works fine. Since this is a FATAL error, it doesn’t appear that there is any way to retry it.

Prior to using this technique, I used the ‘command’ module to call out to SSH directly which was more reliable because I could do retries, but I have an additional requirement in that I can change the user I’m connecting as using set\_fact OR ‘-u’ and this didn’t seem to work with the command module.

Are there any other good patterns to detect when an EC2 instance has completed the entire boot process?

---

<div class="post-metadata">

**Author:** ![Allen\_Sanabria1](https://avatars.discourse-cdn.com/v4/letter/a/85e7bf/32.png) [@Allen\_Sanabria1](https://forum.ansible.com/u/Allen_Sanabria1)\
**Post date:** [June 10, 2016, 5:38pm UTC](https://forum.ansible.com/t/reliable-way-to-detect-when-ec2-instance-is-ready-for-login/21736/2 "2016-06-10T17:38:04Z")

</div>

![](https://us1.discourse-cdn.com/ansible/original/2X/1/119403821505282206a4f9ba36d4bb5c3c383667.png)

I use the command module locally, to validate that I can actually login using ssh.
