Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to use the output of `gcloud` in a script, but the format changes. What should I do?

Tags:

gcloud

I’m using the command gcloud compute instances list in a script, but I’m worried that the exact output format isn’t static. What should I do?

like image 806
Zachary Newman Avatar asked Jan 04 '16 21:01

Zachary Newman


1 Answers

You should use the --format flag, available for most gcloud commands.

For instance, if you’d like to get the exact same output as the current (as of the time of writing of this answer) format, you can run:

$ gcloud compute instances list --format="table(
    name,
    zone.basename(),
    machineType.basename(),
    scheduling.preemptible.yesno(yes=true, no=''),
    networkInterfaces[0].networkIP:label=INTERNAL_IP,
    networkInterfaces[0].accessConfigs[0].natIP:label=EXTERNAL_IP,
    status
)"

The output of this command will not change between releases, even if the default output of the command does (unless the resource being formatted changes; this should be rare).1 Showing the default format for resources in commands is a work in progress.2

You can also specify a format like YAML or JSON for machine-readable output:

$ gcloud compute instances list --format=yaml
$ gcloud compute instances list --format=json

Note that this output contains much more information than is present in the default output for this command; this is the information you have to work with when constructing a custom format.

CSV is another format option. Like table, it requires a projection–a specification for how to print each row.3

$ gcloud compute instances list --format="csv(name,zone,status)"
name,zone,status
example-instance,us-central1-f,RUNNING
...

For more information on the formatting capabilities of gcloud, see the output of gcloud topic formats and gcloud topic projections.


  1. You can see all possible fields by running gcloud compute instances list --format=flattened.
  2. For some commands, like gcloud beta test android locales list, you can pass the --verbosity=info flag and look for INFO: Display format.
  3. This is because CSV data cannot be nested like JSON or YAML, and the data structures being printed may be nested.
like image 186
Zachary Newman Avatar answered Oct 20 '22 19:10

Zachary Newman