1

TL;DR. I want an instance to describe itself while running a startup script.


I'm having a startup.sh shell script (which I can reference with --metadata startup-script-url=gs://bucketname/startup.sh), which depends on a steam.exp expect script. Therefore I'd like to know the name of the bucket, which was used; eg. from meta-data startup-script-url. It is being assumed that both files reside in the same bucket, but only one of them can be referenced.

I'm trying to get the meta-data startup-script-url and then extract the bucket name in shell script (to be added into startup.sh, in order to fetch the gs://bucketname/steam.exp before running it).

What I have tried so far:

gcloud compute instances describe $HOSTNAME \
  --zone=europe-west3-c \
  --project=some-project \
  --flatten="metadata[startup-script-url]"

But this is not portable, as it would need to be the current project ID and current zone.

How to obtain these values in a startup script? I haven't tried printenv yet.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216

2 Answers2

3

One can get the project alike this:

PROJECT_ID=`gcloud config get-value project`

And then obtain the zone with:

gcloud compute instances list \
  --project=$PROJECT_ID \
  --filter=name:$HOSTNAME \
  --format="table[csv,no-heading](zone)"

This requires permission gcloud.compute.instances.list, which role roles/compute.viewer has.

Meanwhile I've also found Google Cloud Game Servers (beta).

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
0

You can get the VM metadata with curl:

STARTUP_SCRIPT_URL=`curl -s "http://metadata.google.internal/computeMetadata/v1/instance/attributes/my-startup-script-url" -H "Metadata-Flavor: Google"`

You can also get other values from the metadata server, like GCP Project ID and the VM's zone. Curl seems to be faster than gcloud:

GCP_PROJECT_ID=`curl -s "http://metadata.google.internal/computeMetadata/v1/project/project-id" -H "Metadata-Flavor: Google"`

GCP_ZONE=$(basename `curl -s "http://metadata.google.internal/computeMetadata/v1/instance/zone" -H "Metadata-Flavor: Google"`)

GCP_REGION="${GCP_ZONE::-2}"

https://cloud.google.com/compute/docs/metadata/default-metadata-values

levidos
  • 47
  • 6