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.

0

2 Answers 2

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).

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

2
  • Sorry, but why would I want to use cURL? This only adds lots of complexity with zero advance. And it also may work in Linux. Oct 23, 2022 at 10:10
  • One benefit would be much faster execution than the python gcloud cli
    – levidos
    Feb 3 at 2:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.