【问题标题】:Filter instances by state with boto3使用 boto3 按状态过滤实例
【发布时间】:2016-11-02 12:24:39
【问题描述】:

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

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

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

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

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

【问题讨论】:

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


    【解决方案1】:
    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)
    

    希望对您有所帮助!

    【讨论】:

    • 过滤这种方式调用:boto3.resources.collection (DEBUG): Calling paginated ec2:describe_instances。这里如何处理分页?
    • 这取决于“停止”和“终止”的正确拼写。假设您可以使用 instance-state-code 和 48 和 80... 有没有办法从某种查找或名称中获取值 48 和 80?这样,如果你拼写错误停止,你会得到一个属性错误,而不是默默地失败并给出误报/否定?例如 boto3.some_package.ec2states.stopped。问题是 ec2.instances.filter 如果您输入错误,它不会抱怨。如果我有错别字,我希望 Python 本身抱怨一个属性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 2019-10-19
    • 2021-11-15
    • 2019-04-04
    • 2021-04-27
    • 2014-03-05
    • 1970-01-01
    相关资源
    最近更新 更多