2

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?

1 Answer 1

4

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.

2
  • 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, 2015 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, 2018 at 2:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .