【问题标题】:Filter instance based on multiple tags in Lambda Python code基于 Lambda Python 代码中的多个标签过滤实例
【发布时间】:2020-07-02 17:54:26
【问题描述】:

我想检查某个实例是否有标签列表。我感兴趣的标签是环境、环境和环境。它们的值是Production、Prod 和production。我正在使用 lambda 函数来检查它,到目前为止我有这个:

response = ec2.describe_tags(
Filters=[
    {
        'Name': 'tag:Environment|Env|environment',
        'Values': [
            'Production|production|Prod',
        ]
    },
    {
        'Name': 'resource-id',
        'Values': [
            instance_id,
        ],
    }
])
print(response)

但这并没有在实例上捕获正确的标签。我相信问题是我试图以“Key1|Key2|Key3”格式捕获多个标签。谁能建议通过多个标签进行过滤的正确方法?谢谢!

【问题讨论】:

    标签: python amazon-web-services amazon-ec2 aws-lambda


    【解决方案1】:

    我认为您必须在 三个单独的电话中进行。至少这是我从我的灭绝者中可以得出的结论。

    我使用的一个例子如下:

    import boto3
    
    from pprint import pprint
    
    ec2 = boto3.client('ec2')
    
    tag_values = ['production', 'Prod', 'Production']
    tag_names = ['Env', 'Environment', 'environment']
    
    results = []
    
    for tag_name in tag_names:
    
        r=ec2.describe_tags(
                Filters=[{
                        'Name':'tag:' + tag_name,
                        'Values': tag_values
              }])
    
        pprint(r)
    
        results.append(r)
    
    
    pprint(results)
    

    【讨论】:

      【解决方案2】:

      您似乎正在尝试使用 lambda 基于 EC2 事件 工作,那么您最好获取基于 EC2 事件中可用的 Instance ID 的实例,获取标签并执行进一步的操作。

      ec2 = boto3.client('ec2')
      specificinstance = ec2.describe_instances(Filters=[
      {
          'Name': 'instance-id',
          'Vdataalues': [
              event["detail"]["EC2InstanceId"]
              ],
      }])
      TAGS=specificinstance["Reservations"][0]["Instances"][0]["Tags"]
      pprint(TAGS) 
      

      或者我没有找到一种方法来根据不同的tag-key 过滤实例,但这里是一个可能有帮助的示例,它根据不同的值进行过滤。

      import boto3  
      client = boto3.client('ec2') 
      filters = [{  
          'Name': "tag:environment",
          'Values': ['prod','production','Production']
          }]
      response = client.describe_instances(Filters=filters)
      print response
      

      如果容器 environmentprod,production,Production 一样,这将过滤

      使用实例 IP 或预留 ID 进行过滤

      import boto3  
      client = boto3.client('ec2') 
      filters = [{  
          'Name': "tag:environment",
          'Values': ['prod,production,Production']
          },
          {
          'Name': 'instance-id',
          'Values': [
              'i-123456789',
              ],
      }]
      response = client.describe_instances(Filters=filters)
      print response
      

      【讨论】:

        猜你喜欢
        • 2018-01-09
        • 1970-01-01
        • 2019-09-10
        • 2018-05-16
        • 1970-01-01
        • 2022-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多