Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 649
Evgeny Timoshenko Avatar asked Apr 03 '15 14:04

Evgeny Timoshenko


3 Answers

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

like image 72
Antxon Avatar answered Nov 15 '22 07:11

Antxon


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

like image 41
JasonS Avatar answered Nov 15 '22 09:11

JasonS


If you have to ensure ssh is available, there is a script for that.

#!/usr/bin/env bash

function wait_vm_up {
  local counter=0

  local readonly project=${1:?"project required"}
  local readonly instance=${2:?"instance required"}
  local readonly zone=${3:?"zone required"}
  local readonly user=${4:?"user required"}
  local readonly maxRetry=${5:-100}

  echo "Project: $project"
  echo "Instance: $instance"
  echo "MaxRetry: $maxRetry"

  while true ; do
    if (( $counter == $maxRetry )) ; then
      echo "Reach the retry upper limit $counter"
      exit 1
    fi

    gcloud compute ssh --quiet --zone "$zone" "$user@$instance" --tunnel-through-iap --project "$project" --command="true" 2> /dev/null

    if (( $? == 0 )) ;then
      echo "The machine is UP !!!"
      exit 0
    else
      echo "Maybe later? $counter"
      ((counter++))
      sleep 1
    fi
  done
}

wait_vm_up $@
like image 36
Wade Xing Avatar answered Nov 15 '22 07:11

Wade Xing