如何確保一個 GCE 實體RUNNING在連接之前是存在的?
因為這僅在實體狀態已經為時才有效RUNNING:
gcloud compute ssh --zone $ZONE --project $PROJECT $INSTANCE_NAME
uj5u.com熱心網友回復:
似乎有三種不同的實體狀態RUNNING:STOPPING和TERMINATED。
--允許傳遞 SSH 引數,如-o ConnectTimeout=60 -o ConnectionAttempts=3.
#!/bin/bash
PROJECT=$1
ZONE=$2
INSTANCE_NAME=$3
SSH_DEBUG=false
IAP_TUNNEL=false
TROUBLESHOOT=false
TIMEOUT=60
ATTEMPTS=3
if [ $# != 3 ]; then
echo "Usage: gcloud_ssh.sh PROJECT ZONE INSTANCE_NAME"
exit 1
else
declare -a PARAM
PARAM=(--project "$PROJECT" --zone "$ZONE" "$INSTANCE_NAME")
fi
function getInstanceStatus() {
gcloud compute instances describe "${PARAM[@]}" --format="get(status)"
}
function whileStopping() {
echo "GCE instance \`$INSTANCE_NAME\` is shutting down."
STATUS=$(getInstanceStatus)
}
function startInstance() {
echo "GCE instance \`$INSTANCE_NAME\` will be brought up."
gcloud compute instances start "${PARAM[@]}"
STATUS=$(getInstanceStatus)
}
STATUS=$(getInstanceStatus)
# Loop while the instance status is `STOPPING`.
while [[ "$STATUS" = "STOPPING" ]]; do whileStopping; done
# Start instance, once the instance status is `TERMINATED`.
if [[ "$STATUS" = "TERMINATED" ]]; then startInstance; fi
# This `if` statement might never be the case.
if [[ "$STATUS" != "RUNNING" ]]; then exit 1; fi
# Open SSH, when the instance status is `RUNNING`.
if [[ $IAP_TUNNEL = true ]]; then PARAM=("${PARAM[@]}" --tunnel-through-iap); fi
if [[ $TROUBLESHOOT = true ]]; then PARAM=("${PARAM[@]}" --troubleshoot); fi
PARAM=("${PARAM[@]}" -- -o ConnectTimeout="$TIMEOUT" -o ConnectionAttempts="$ATTEMPTS")
if [[ $SSH_DEBUG = true ]]; then PARAM=("${PARAM[@]}" -v); fi
gcloud compute ssh "${PARAM[@]}"
然后可以將實體定義為alias檔案中的快捷方式~/.bash_aliases:
alias ssh_xyz='/home/scripts/gcloud_ssh.sh project-name zone-name instance-name'
這個腳本需要角色compute.instanceAdmin.v1并且有選項SSH_DEBUG, IAP_TUNNEL, TROUBLESHOOT. 對于關閉遠程實體,這將是:sudo poweroff.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/493724.html
