Reputation: 552
My requirement is to filter based on 2 conditions:
I can achieve this by writing 2 separate custom filters, but I want to know if I can achieve the same in single filter.
My Code:
stopped_filter = Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}]
stopped_instances = ec2.instances.filter(Filters=stopped_filter)
tag_filter = Filters=[{'Name':'tag-key', 'Values':['doaf']}]
tagged_instances = ec2.instances.filter(Filters=tag_filter)
What I have tried:
filter = Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}, {'Name':'tag-key', 'Values':['doaf']}]
stopped_and_tagged_instances = ec2.instances.filter(Filters=filter)
Upvotes: 1
Views: 2006
Reputation: 270184
This line:
filter = Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}, {'Name':'tag-key', 'Values':['doaf']}]
Should be:
filter = [{'Name': 'instance-state-name', 'Values': ['stopped']}, {'Name':'tag-key', 'Values':['doaf']}]
Full example:
import boto3
ec2 = boto3.resource('ec2', region_name='ap-southeast-2')
filter = [{'Name': 'instance-state-name', 'Values': ['stopped']}, {'Name':'tag-key', 'Values':['Foo']}]
stopped_and_tagged_instances = ec2.instances.filter(Filters=filter)
print([i.id for i in stopped_and_tagged_instances])
Upvotes: 2