shittyk8s
shittyk8s

Reputation: 3

Format gcloud compute instances list to get single metadata value

As part of some GCP admin automation I'm trying to run a gcloud compute instances list command to return a few instance properties, one of which is a single metadata property. I cannot find in the documentation how to return only a single metadata property.

This is what I would think is correct based on the doc, but I don't get any metadata properties returned...

gcloud compute instances list --filter="name~^my-machine.*-type" --zones=zone1,zone2,zone3 --format="json(name,metadata.items.MY_VALUE)"

How can I return a single metadata value?

Upvotes: 0

Views: 1598

Answers (1)

DazWilkin
DazWilkin

Reputation: 40061

Eesh... this was not obvious ;-)

KEY=...

gcloud compute instances list \
--project=${PROJECT} \
--format="value(metadata.items.extract("${KEY}"))"

See extract

I'm not sure why it works.

In my case:

gcloud compute instances list \
--project=${PROJECT} \
--format="value(metadata.items)"

Yields:

{'key': 'gce-container-declaration', 'value': "..."};
{'key': 'google-logging-enabled', 'value': 'true'}

NOTE a semi-colon separated list of JSON objects

So, metadata.items appears to be a list of JSON objects {"key": $KEY, "value": $VALUE} and I think this why you can't walk down through the values using something ... metadata.items.key["google-logging-enabled"] or similar.

When I initially looked using YAML, this wasn't obvious and I think, even though the YAML looks flat, the items are embedded and the --format=yaml is doing something clever:

gcloud compute instances list \
--project=${PROJECT} \
--format="yaml(metadata.items)"
---
metadata:
  items:
  - key: gce-container-declaration
    value: |-
      ...
  - key: google-logging-enabled
    value: 'true'

But:

gcloud compute instances list \
--project=${PROJECT} \
--format="value(metadata.items.extract("gce-container-declaration"))"

Yields:

spec:
  containers:
    - name: instance-1
      image: ...
      stdin: false
      tty: false
  restartPolicy: Always

Upvotes: 0

Related Questions