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:
- query the metadata to get instance hostname and zone
- assume the hostname is the same as the instance name (is this safe?)
- perform a regex on the hostname to strip out the domain (is this safe?)
- 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:
You will also need to make sure that the service account of the VM instance is a project member with edit permission.