问题
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?
回答1:
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:
- Get the IP for instance $my_name
- 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
回答2:
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
回答3:
I think that startup scripts do the work for you :D
or using the REST APIs you can polling the instance status
回答4:
You can use this command: gcloud compute instances describe 'instance name' --zone 'zone name' | grep "status: RUNNING"
If you get the exact output status: RUNNING it'll indicate the instance is up and running.
来源:https://stackoverflow.com/questions/29434076/how-to-ensure-google-cloud-compute-instance-is-up-and-running