如何确保 Google 云计算实例已启动并且 运行

How to ensure Google Cloud Compute instance is up and running

我从 shell 脚本创建 Google 云计算实例,然后通过 ssh 在该实例上启动多个命令。

如何确保实例中的操作系统已启动并运行正在运行?

例如:

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

那我也想运行 gcloud compute ssh \ "$my_name" --zone "$my_zone" \ --command 'sudo docker stop $(sudo docker ps -q -a)'

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

据我了解,如果实例未启动,第二个命令可能会因连接拒绝而失败。

如何确保实例已启动并准备好接受 ssh 连接?

我认为 startup scripts 为您完成工作 :D

或使用 REST APIs 您可以轮询实例状态

您可以使用此命令:gcloud compute instances describe 'instance name' --zone 'zone name' | grep "status: RUNNING"

如果您获得准确的输出 status: 运行 它将指示实例已启动并且 运行.

发送命令前检查SSH端口是否打开即可。在实例 OS 启动之前,SSH 服务器不会启动:

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

解释:

  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

简单的跨平台解决方案:

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

循环直到你得到 errorLevel=0

如果您必须确保 ssh 可用,可以使用脚本。

#!/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 $@

简单的命令行或别名。

alias gcp_status_MY_MACHINE='gcloud compute instances describe salesforce --zone "ZONE" --project "PROJECT" | grep status'

如果您只有一个项目并且没有指定区域它仍然可以工作,这只是详细版本。