Search code examples
google-compute-enginegce-instance-group

How to get external IPs of specific instance group on GCE - Google Compute Engine?


$ gcloud --format="value(networkInterfaces[0].accessConfigs[0].natIP)" compute instances list

This command currently works to get ALL the ips that are active but if I have multiple instance groups lets say one is called: Office, and the other is called Home

How do I get just the instance IPs in instance group "Office" only


Solution

  • Unfortunately there is no easy way to do it. Ideally it should be part of gcloud instance-groups list-instances API, but it does not return IP addresses, just instance names.

    So far, I've managed to get the desired response by executing 2 different commands.

    1. To get names of all instances

    instances=$(gcloud beta compute instance-groups list-instances <Enter Your Instance Group Name Here> | awk -v ORS=, '{if(NR>1)print $1}')

    1. To get External IPs

    gcloud --format="value(networkInterfaces[0].accessConfigs[0].natIP)" compute instances list --filter="name=( $instances )"

    A breakdown / explanation of 1st Command:

    • gcloud beta compute instance-groups list-instances <Enter Your Instance Group Name Here> will return all instances in that Instance Group
    • awk -v ORS=, will replace all lines with , and returns a single comma separated string
    • 'if(NR>1) will exclude first line of response which is NAME
    • print $1 will get only the 1st column which are instance names
    • instances=$(<Entire Gcloud Command with awk) will capture the response in variable

    2nd Command should be self explanatory.

    It will be great if someone can combine these 2 commands into a single command.