Ari
Ari

Reputation: 6149

List instances that do not have a specific label in GCP using python

Is it possible to filter out instances on a wildcard or regex? I essentially just want GCE instances, not GKE or instances provisioned by other services.

I've found that GCP service created instances have a label attached that typically starts with goog-*. From GCP Cloud Logging I can filter these out fine but there's doesn't seem to be any support for regex in the python client.

from googleapiclient.discovery import build

service = build('compute', 'v1', credentials=credentials)
request = service.instances().aggregatedList(project="my-project", filter="labels != goog-*")

Upvotes: 3

Views: 1164

Answers (1)

Wojtek_B
Wojtek_B

Reputation: 4443

While it's not a documented feature that you get those goog-something labels when deploying a new cluster or even a single VM solution - in most cases it will be true.

To get get a nice list of all instances with labels other than goog- run:

gcloud compute instances list --filter=-labels:'goog-*'

Applying it to Python it can look like this:

import os
os.system('gcloud compute instances list --filter=-labels:"goog-*"')

or you can use subprocess.run (as described here).

If in any doubt you can have a look at the gcloud compute instances list docs and how to use a filter option.

Upvotes: 1

Related Questions