How do I get instance-group name from inside of a GCE instance?

850 views Asked by At

This command gives me the instance name:

curl -X GET http://metadata.google.internal/computeMetadata/v1/instance/name -H 'Metadata-Flavor: Google'

This command gives me the instance zone:

curl -X GET http://metadata.google.internal/computeMetadata/v1/instance/zone -H 'Metadata-Flavor: Google

I can't figure out how to get the instance-group-name similarly?

I need this set self-destruct command in a GCE instance:

gcloud compute instance-groups managed delete-instances $INSTANCE_GROUP_NAME --instances=$NAME --zone=$ZONE
2

There are 2 answers

0
Kolban On

Looking at this document:

https://cloud.google.com/compute/docs/instance-groups/getting-info-about-migs#checking_if_a_vm_instance_is_part_of_a_mig

There appears to be a metadata key value called "created-by". This appears to have a value similar to:

projects/123456789012/zones/us-central1-f/instanceGroupManagers/igm-metadata

Looking at this, we can appear to parse the string and the value following "instanceGroupManagers" appears to provide the information we are looking for.

0
Vi Pau On

I wrote a small script for this, let me know if it works for you:

#!/bin/bash

# exit if cURL not present
command -v curl >/dev/null || { echo 'curl not found! exiting' >> /dev/stderr ; exit 2; }

# try to fetch MIG name
migname=$(curl --silent --fail -H 'Metadata-Flavor: Google'  "http://metadata.google.internal/computeMetadata/v1/instance/attributes/created-by")

# if var is empty, instance is not part of MIG
# echo to stderr so you can safely use this in a script
[ -z "$migname" ] && { echo 'instance is not part of a MIG.' >> /dev/stderr ; exit 3; }

# otherwise, extract after last slash.
basename "$migname"