Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/amazon-web-services/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
编写自定义过滤器的更好方法| Python-AWS-Boto3_Python_Amazon Web Services_Amazon Ec2_Boto3 - Fatal编程技术网

编写自定义过滤器的更好方法| Python-AWS-Boto3

编写自定义过滤器的更好方法| Python-AWS-Boto3,python,amazon-web-services,amazon-ec2,boto3,Python,Amazon Web Services,Amazon Ec2,Boto3,我的要求是根据两个条件进行过滤: 停止的实例 具有特定标记的实例 我可以通过编写两个独立的自定义过滤器来实现这一点,但我想知道是否可以在单个过滤器中实现相同的功能 我的代码: stopped_filter = Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}] stopped_instances = ec2.instances.filter(Filters=stopped_filter) ta

我的要求是根据两个条件进行过滤:

  • 停止的实例
  • 具有特定标记的实例
  • 我可以通过编写两个独立的自定义过滤器来实现这一点,但我想知道是否可以在单个过滤器中实现相同的功能

    我的代码:

        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)
    
    我尝试过的:

        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)
    
    这一行:

    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']}]
    
    完整示例:

    导入boto3
    ec2=boto3.resource('ec2',region_name='ap-Southast-2')
    筛选器=[{'Name':'实例状态名称','Values':['stopped']},{'Name':'tag-key','Values':['Foo']}]
    停止和标记的\u实例=ec2.instances.filter(Filters=filter)
    打印([停止的\u和标记的\u实例中的i的i.id])
    
    关于使用标签搜索,这是一个悬而未决的问题:你可以看它。你检查了吗?谢谢,伙计,我现在修改了我的问题。讨论中似乎没有结论。。另外,上面的讨论有一个稍微不同的上下文感谢您的建议,您的脚本返回以下内容:[ec2.Instance(id='i-xxxxxxxxx')、ec2.Instance(id='i-xxxxxxxxx')、…]我只希望在输出中提取“i-xxxxxxxxx”部分。不使用正则表达式。它返回一个实例集合。您可以通过
    .id
    提取实例。我已经编辑了我的答案,以展示如何。永远不需要正则表达式,因为代码处理的是对象,而不是字符串。