Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering ec2-instances with boto

I use tags to keep track of my EC2 instances, such as (Project, Environment). I have a use case where I need to filter only those instances that belong to a specific project and to a specific environment.

When I use filter with boto and pass these two values I get a result that does a OR rather than a AND of the filters and so I am receiving a list of instances that belong to different projects but same environment.

Now I can use two lists and then compare the instances in each and get the desired set of instances, but is there a better way of getting this done?

Here is what i am doing:

conn = ec2.EC2Connection('us-east-1',aws_access_key_id='XXX',aws_secret_access_key='YYY')
reservations = conn.get_all_instances(filters={"tag-key":"project","tag-value":<project-name>,"tag-key":"env","tag-value":<env-name>})
instances = [i for r in reservations for i in r.instances]

Now the instance list that I am getting gives all the instances from the specified project irrespective of the environment and all the instances from the specified environment irrespective of the project.

like image 520
user3228188 Avatar asked Apr 14 '14 06:04

user3228188


Video Answer


1 Answers

You can use the tag:key=value syntax to do an AND search on your filters.

import boto.ec2

conn = boto.ec2.connect_to_region('us-east-1',aws_access_key_id='xx', aws_secret_access_key='xx')
reservations = conn.get_all_instances(filters={"tag:Name" : "myName", "tag:Project" : "B"})
instances = [i for r in reservations for i in r.instances]
print instances

See EC2 API for details http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstances.html

The problem with the syntax you used is that a Python dict has unique keys, so the second tag-key entry overwrites the first one :-(

Seb

like image 60
Sébastien Stormacq Avatar answered Oct 23 '22 15:10

Sébastien Stormacq