使用boto3按状态过滤实例

时间:2016-06-30 12:03:25

标签: python-3.x amazon-ec2 boto3

尝试使用boto3来描述我的所有实例,并过滤当前未运行的每个实例。 使用此帖子作为构建我的过滤器的参考 - http://rob.salmond.ca/filtering-instances-by-name-with-boto3/

当我尝试使用此过滤器按状态过滤实例时 -

filters = [{
'Name': 'tag:State',
'Values': ['running']
}]

查询返回空(这是有道理的,因为状态值嵌套在它自己的字典中。

我的问题是 - 如何使用filters参数访问嵌套标记?

1 个答案:

答案 0 :(得分:15)

session = boto3.Session(region_name="us-east-1")

ec2 = session.resource('ec2', region)

instances = ec2.instances.filter(
        Filters=[{'Name': 'instance-state-name', 'Values': ['stopped', 'terminated']}])

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

希望有所帮助!!