使用 boto3 按状态过滤实例

Filter instances by state with boto3

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

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

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

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

我的问题是 - 如何使用过滤器参数访问嵌套标签?

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)

希望对您有所帮助!!