Wait for VM Startup with SSH: A One-Liner Guide

While working on a github pipeline, the need came up to wait until a VM is up. The “sufficient” precondition being that an SSH connection becomes possible. Because of … reasons, this had to be a one-liner. I came up with the one below:

vm_public_ip=....
timeout 120s bash -c 'while true; do ssh -tt -o StrictHostKeyChecking=no -o PubkeyAuthentication=no -o PasswordAuthentication=no -o KbdInteractiveAuthentication=no -o ChallengeResponseAuthentication=no -o BatchMode=yes "$vm_public_ip" 2>&1 | grep -q -i "Permission denied" && exit 0 || echo not reachable yet; sleep 2; done'

timeout” will execute a command and wait till it exits or until a timeout occurs (in which case it’ll fail with an exit code). The peculiar ssh statement with the many options disables all authentication mechanisms so that any authentication attempt must fail, regardless of credentials, “-tt” suppresses a complaint about missing terminals because this runs inside a CI pipeline. Thus, a successful connection would actually fail with a “Permission denied” message. The while loop is self-explanatory.

Quick functional overview: timeout gives the discovery mechanism two minutes before failing. Bash is just a process wrapper around the script with the while loop. The while loop runs “indefinitely”, unless either timed out or an SSH connection succeeds. A successful SSH connection will fail with a permission denied message, which grep picks up and exits the loop. If the VM is unreachable (down or without network), SSH will fail with a different message, continuing the loop.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.