I'm trying to write a script that allows an instance to terminate itself when it has completed its tasks. So far this is what I have come up with:

  1. query the metadata to get instance hostname and zone
  2. assume the hostname is the same as the instance name (is this safe?)
  3. perform a regex on the hostname to strip out the domain (is this safe?)
  4. call gcloud compute instances delete [name] --zone [zone] --quiet

It all seems a bit brittle and I was wondering if there is a better solution. In particular I know I can query for the instance id but it seems all the gcloud commands expect a name not an id. Is this correct?


For Linux VM instances try this script instead:

VMNAME=$(curl -H Metadata-Flavor:Google http://metadata/computeMetadata/v1/instance/hostname | cut -d. -f1)
ZONE=$(curl -H Metadata-Flavor:Google http://metadata/computeMetadata/v1/instance/zone | cut -d/ -f4)
gcloud compute instances delete $VMNAME --zone $ZONE --quiet

You will also need to make sure that the service account of the VM instance is a project member with edit permission.

  • 4
    For the lazy, here's a simple oneliner that pulls the correct zone from the metadata servers: gcloud compute instances delete $(hostname) --zone $(curl -H Metadata-Flavor:Google http://metadata.google.internal/computeMetadata/v1/instance/zone|cut -d/ -f4) --quiet
    – James
    Jun 2 '15 at 10:27
  • Here is the complete script for getting the metadata information on GCP - github.com/baskaran-md/gcp-metadata (similar to ec2-metadata, if you are familiar with)
    – Baskar
    Mar 30 '18 at 2:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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