GCE metadata – get instance name

google-cloud-platformgoogle-compute-engine

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?

Best Answer

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.