Max Cameron
Max Cameron

Reputation: 4887

Filter boto instance list by 'tag: component': 'foo', or 'tag:component': 'bar'

I'd like to get a list of instances in boto either have a "component" tag of foo or bar.

Is there a way to avoid making two requests and munging the objects?

Upvotes: 6

Views: 8054

Answers (2)

Onevarez
Onevarez

Reputation: 1154

# With boto3
def get_instances_by_tag_value( tag, value):

   ec2 = boto3.resource('ec2')

   instances = ec2.instances.filter(
       Filters=[{'Name': 'tag:' + tag, 'Values': [value]}])

   for instance in instances:
      print(instance.id, instance.instance_type)

get_instances_by_tag_value('tagname', 'tagvalue') # call function

Upvotes: 3

garnaat
garnaat

Reputation: 45906

This should find all instances that have a tag called component with a value of either foo or bar:

import boto.ec2
c = boto.ec2.connect_to_region('us-west-2')
reservations = c.get_all_instances(filters={'tag:component':['foo', 'bar']})

Does that solve your problem?

Upvotes: 14

Related Questions