1

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
Grzenio
  • 35,875
  • 47
  • 158
  • 240
stkvtflw
  • 12,092
  • 26
  • 78
  • 155
  • Might it be the case that the managed instance group that caused the creation of the Compute Engine isn't recorded/associated with the instance. Instead, we may be able to invoke API and the instance groups what compute engine instances they consist of. – Kolban Dec 08 '20 at 16:49

2 Answers2

1

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"
Vi Pau
  • 337
  • 1
  • 4
0

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.

Kolban
  • 13,794
  • 3
  • 38
  • 60