Skip to main content
 首页 » 编程设计

python之用于检查特定标记是否不存在的 Lambda 函数-python

2024年09月07日8davidwang456

我正在尝试获得以下信息:

获取所有 EC2 实例:

  1. 标有标签所有者和值未知或未知
  2. 缺少标签所有者

我能够完成 1) 但不知道如何获得 2)

import boto3    
import collections      
import datetime      
import time      
import sys  
 
ec = boto3.client('ec2', 'eu-west-1')      
ec2 = boto3.resource('ec2', 'eu-west-1')      
 
 
def lambda_handler(event, context):            
    instance_ids = [] 
    reservations = ec.describe_instances(      
        Filters=[      
            {'Name': 'tag:Owner', 'Values': ['Unknown', 'unknown']},      
        ]      
    ).get('Reservations', [])  
 
    for reservation in reservations: 
          instances = reservation['Instances'] 
          for instance in instances: 
              instance_ids.append(instance['InstanceId']) 
 
    print("Stopping instances: {}".format(','.join(instance_ids))) 

请您参考如下方法:

正如我在评论中所说,您想放弃 Owner 过滤器,这样您的响应也包括没有 Owner 标签的实例,然后您可以在本地进行过滤。

reservations = ec.describe_instances().get('Reservations', []) 
for reservation in reservations: 
    for instance in reservation['Instances']: 
        tags = {} 
        for tag in instance['Tags']: 
            tags[tag['Key']] = tag['Value'] 
 
        if not 'Owner' in tags: 
            print instance['InstanceId'] + " does not have Owner tag" 
        elif tags['Owner'] in ['Unknown', 'unknown']: 
            print instance['InstanceId'] + " has [U|u]nknown Owner tag" 

如果您的帐户中有大量实例,则对 describe_instances 的响应可能会分页,您也必须处理这个问题。