Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Compute Engine API - Filtering Instances or Other Lists Using Labels / Tags

With the gcloud command line tool I can do:

$ gcloud compute instances list --filter='tags.items:development'

The documentation claims: "..you can also filter on nested fields. For example, you could filter on instances that have set the scheduling.automaticRestart field to true. Use filtering on nested fields to take advantage of labels to organize and search for results based on label values." But no examples are provided, so it's not clear how one actually goes about this.

I've tried labels.development eq *.*, labels eq *development*, labels:development et al.. I've also tried setting the verbosity of the of the command line client to info and looking through the output, as well as monitoring requests that go to the API from the Compute Engine web console, but neither has gotten me anywhere.

like image 591
pnovotnak Avatar asked May 17 '16 08:05

pnovotnak


1 Answers

Finding Tags with regular expression filters

I'm struggling with the same issue but I think that regular expressions solve the problem.

I have many instances with multiple tags but I can search across all tags with the '~' operator e.g. to find all servers with the production tag:

gcloud compute instances list --filter='tags.items~^production$'

For many servers the 'production' tag is the third entry in tags.items yet the regexp finds it.

This seems to work but I can't find any documentation that specifically says that it should work. The nearest is the section on topic filters which mentions this

key ~ value True if key matches the RE (regular expression) pattern value.


You can also search for multiple tags

gcloud compute instances list --filter='tags.items~^production$ AND tags.items~^european$'

which would find all servers with the two tags 'production' and 'european'


Tags v Custom metadata

If you want something a bit more flexible than tags (which can only be present or missing), you can attach your own custom multi-valued metadata to an instance (via the UI, command-line or API). You can then search for particular values of that item.

For example suppose I have different instances supporting eCommerce for different brands, I could attach a custom 'brand' metadata item to each server and then find all of the servers which run my "Coca-Cola" brands via ..

gcloud compute instances list --filter="metadata.items.key['brand']['value']='Coca-Cola'"

... and my 'Pepsi Cola' servers with ...

gcloud compute instances list --filter="metadata.items.key['brand']['value']='Pepsi Cola'"


Finding Metadata with regular expression filters

You probably guessed this already but the regular expression operator also works with metadata filters so you can do

gcloud compute instances list --filter="metadata.items.key['brand']['value']~'Cola'"

like image 197
Chris McCauley Avatar answered Sep 28 '22 13:09

Chris McCauley