GCP Compute EngineのVMインスタンスをGUIから再起動する方法が見つからなかったため、スクリプトを作成しました。以下が作成したスクリプトです。
保存場所: ~/.local/bin/gcp-instance-restart.sh
#!/bin/bash
# 必要な環境変数のチェック
if [[ -z "${PROJECT_ID}" ]] || [[ -z "${ZONE}" ]] || [[ -z "${INSTANCE_NAME}" ]]; then
echo "使用方法:"
echo "以下の環境変数を設定してください:"
echo " PROJECT_ID - GCPプロジェクトID"
echo " ZONE - GCPゾーン"
echo " INSTANCE_NAME - VMインスタンス名"
echo ""
echo "例:"
echo " PROJECT_ID= ZONE= INSTANCE_NAME= $0"
exit 1
fi
# VMの停止
echo "Stopping VM instance: $INSTANCE_NAME"
gcloud compute instances stop "$INSTANCE_NAME" --zone="$ZONE" --project="$PROJECT_ID"
# 停止を確認
echo "Waiting for the VM to stop..."
while true; do
STATUS=$(gcloud compute instances describe "$INSTANCE_NAME" --zone="$ZONE" --project="$PROJECT_ID" --format="value(status)")
if [[ "$STATUS" == "TERMINATED" ]]; then
echo "VM has stopped."
break
fi
echo "Current status: $STATUS. Retrying in 5 seconds..."
sleep 5
done
# VMの起動
echo "Starting VM instance: $INSTANCE_NAME"
gcloud compute instances start "$INSTANCE_NAME" --zone="$ZONE" --project="$PROJECT_ID"
# 起動を確認
echo "Waiting for the VM to start..."
while true; do
STATUS=$(gcloud compute instances describe "$INSTANCE_NAME" --zone="$ZONE" --project="$PROJECT_ID" --format="value(status)")
if [[ "$STATUS" == "RUNNING" ]]; then
echo "VM is running."
break
fi
echo "Current status: $STATUS. Retrying in 5 seconds..."
sleep 5
done
echo "VM restart process completed."
実行例:
$ PROJECT_ID=test-project ZONE=asia-northeast1-b INSTANCE_NAME=test-instance ~/.local/bin/gcp-instance-restart.sh
Stopping VM instance: test-instance
Stopping instance(s) test-instance...done.
Updated [].
Waiting for the VM to stop...
VM has stopped.
Starting VM instance: test-instance
Starting instance(s) test-instance...done.
Updated [].
Instance internal IP is 11.111.1.1
Instance external IP is 11.11.11.111
Waiting for the VM to start...
VM is running.
VM restart process completed.