我的要求是根据2个条件进行过滤:
我可以通过编写2个单独的自定义过滤器来实现这一目标,但是我想知道是否可以在单个过滤器中实现相同的目标。
我的代码:
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)
我尝试过的事情:
filter = Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}, {'Name':'tag-key', 'Values':['doaf']}]
stopped_and_tagged_instances = ec2.instances.filter(Filters=filter)
答案 0 :(得分:2)
此行:
filter = Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}, {'Name':'tag-key', 'Values':['doaf']}]
应该是:
filter = [{'Name': 'instance-state-name', 'Values': ['stopped']}, {'Name':'tag-key', 'Values':['doaf']}]
完整示例:
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])