Search code examples
bashgoogle-cloud-platformgoogle-compute-enginemetadatagcloud

How to get the current Zone & Project ID in a GCE startup script?


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.


Solution

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