Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list of internal IP addresses of GCE instances

I have a bunch of instances running in GCE. I want to programmatically get a list of the internal IP addresses of them without logging into the instances (locally).

I know I can run:

gcloud compute instances list

But are there any flags I can pass to just get the information I want? e.g.

gcloud compute instances list --internal-ips

or similar? Or am I going to have to dust off my sed/awk brain and parse the output?

I also know that I can get the output in JSON using --format=json, but I'm trying to do this in a bash script.

like image 836
Spanky Avatar asked Jan 16 '15 22:01

Spanky


2 Answers

The simplest way to programmatically get a list of internal IPs (or external IPs) without a dependency on any tools other than gcloud is:

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

This uses --format=value which also requires a projection which is a list of resource keys that select resource data values. For any command you can use --format=flattened to get the list of resource key/value pairs:

$ gcloud --format=flattened compute instances list
like image 59
aculich Avatar answered Sep 21 '22 22:09

aculich


The best possible way would be to have readymade gcloud command use the same as and when needed.

This can be achieved using table() format option with gcloud as per below:

gcloud compute instances list --format='table(id,name,status,zone,networkInterfaces[0].networkIP :label=Internal_IP,networkInterfaces[0].accessConfigs[0].natIP :label=External_IP)'

What does it do for you?

  • Get you data in clean format
  • Give you option to add or remove columns

Need additional columns? How to find column name even before you run the above command?

Execute the following, which will give you data in raw JSON format consisting value and its name, copy those names and add them into your table() list. :-)

gcloud compute instances list --format=json

Plus Point: This is pretty much same syntax you can tweak with any GCP resources data to fetch including with gcloud, kubectl etc.

like image 31
pankaj singh Avatar answered Sep 20 '22 22:09

pankaj singh