Google Compute Engineのstartup scriptsを試してみる

Google Compute Engineのstartup scripts(起動スクリプト)の機能を試してみました。

(最近GCPの「やってみた」系の記事が続いています)

やってみる

インスタンス作成。

$ gcloud compute instances create sample1 --image-project ubuntu-os-cloud --image-family ubuntu-2004-lts

startup-script という名前のメタデータとしてスクリプトの中身を文字列で直接指定すればよいようです。起動した日時をテキストファイルに書き残すスクリプトを指定してみました。

$ gcloud compute instances add-metadata sample1 --metadata startup-script="date > /startup-date.txt"

メタデータを確認してみます。

$ gcloud compute instances describe sample1 --format json | jq ".metadata.items"
[
  {
    "key": "startup-script",
    "value": "date > /startup-date.txt"
  }
]

起動していたインスタンスだったので、いったんSTOP。

$ gcloud compute instances stop sample1
Stopping instance(s) sample1...done.
Updated [https://compute.googleapis.com/compute/v1/projects/xxxxxxxx/zones/asia-northeast1-a/instances/sample1].

STOPが完了するまでコマンドは待ってくれるようです。

続いて起動。

$ gcloud compute instances start sample1
Starting instance(s) sample1...done.
Updated [https://compute.googleapis.com/compute/v1/projects/xxxxxxxx/zones/asia-northeast1-a/instances/sample1].
Instance internal IP is 10.xxx.xxx.xxx
Instance external IP is 34.xxx.xxx.xxx

startコマンドも起動が完了するまで待ってくれます。しかも、起動完了したら、取得したIPアドレスがコンソールに表示されるんですね。便利。

$ ssh suzuki@34.xxx.xxx.xxx cat /startup-date.txt
Mon Apr 12 13:49:34 UTC 2021

add-metadataコマンドで直接スクリプトの中身を指定するのではなく、ローカルファイルに置いてから指定することもできるようです。

ローカルのカレントディレクトリに startup-script.txt という名前でスクリプトを置きます。

$ cat > startup-script.txt
echo Hello >> /startup-date.txt
date >> /startup-date.txt

このファイルをメタデータで指定します。ファイルの中身がメタデータで登録されます。

$ gcloud compute instances add-metadata sample1 --metadata-from-file startup-script=./startup-script.txt
$ gcloud compute instances describe sample1 --format json | jq ".metadata.items"
[
  {
    "key": "startup-script",
    "value": "echo Hello >> /startup-date.txt\ndate >> /startup-date.txt\n"
  }
]

再起動。

$ gcloud compute instances stop sample1 && gcloud compute instances start sample1
Stopping instance(s) sample1...done.
Updated [https://compute.googleapis.com/compute/v1/projects/xxxxxxxx/zones/asia-northeast1-a/instances/sample1].
Starting instance(s) sample1...done.
Updated [https://compute.googleapis.com/compute/v1/projects/xxxxxxxx/zones/asia-northeast1-a/instances/sample1].
Instance internal IP is 10.xxx.xxx.xxx
Instance external IP is 34.xxx.xxx.xxx
$ ssh suzuki@34.xxx.xxx.xxx cat /startup-date.txt
Mon Apr 12 13:49:34 UTC 2021
Hello
Mon Apr 12 13:58:34 UTC 2021

追記 2021/04/20

Google Compute Engineのstartup scriptsをgcloudコマンドで取得