How to ensure Google Cloud Compute instance is up and running

I create Google Cloud Compute instance from the shell script, then launch several commands on that instance via ssh.

How to ensure that operating system in the instance is up and running?

For instance:

gcloud compute instances create "$my_name" \ --tags "http-server" \ --image container-vm \ --metadata-from-file google-container-manifest="container.yml" \ --zone "$my_zone" \ --machine-type g1-small

then I want to run either gcloud compute ssh \ "$my_name" --zone "$my_zone" \ --command 'sudo docker stop $(sudo docker ps -q -a)'

or gcloud compute copy-files \ some.conf root@"$my_name":/existing_dir/ \ --zone "$my_zone"

As far as I understand, the second command may fail with connection refuse if the instance is not up.

How to ensure that instance is up and ready to accept ssh connection?


Just check that SSH port is open before sending the command. SSH server won't be up until the instance OS is up:

IP=$(gcloud compute instances list | awk '/'$my_name'/ {print $5}')
if nc -w 1 -z $IP 22; then
    echo "OK! Ready for heavy metal"
    : Do your heavy metal work
else
    echo "Maybe later?"
fi

Explanation:

  1. Get the IP for instance $my_name
  2. Check if port 22 is accepting incoming connections.

-w: Connection timeout (1 second should be more that enough)

-z: Check only if port is open and exit inmediately


easy cross-platform solution:

gcloud compute --verbosity error --project "MYPROJECT" ssh "MYINSTANCE" -- "echo instance now up" -o StrictHostKeyChecking=no

loop that until you get errorLevel=0