将Lambda python条件添加到标记EC2实例

2024-04-26 00:23:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建EC2标签,以防出现某些情况

Lambda函数只应在实例没有标记(Key='DoNotTerminate',Value='True')时标记实例

目前,Lambda函数正在标记每个实例,而不管条件如何

谢谢你的帮助

def lambda_handler(event, context): 
    instance_ids = []
    for reservation in boto_response['Reservations']:
        for instance in reservation['Instances']:
            if instance['State']['Name'] == 'running':
                tags = {}
                for tag in instance['Tags']:
                    tags[tag['Key']] = tag['Value'] 
                    instance_ids.append(instance['InstanceId'])
                    if (tag['Key'] == 'DoNotTerminate' and tag['Value'] == 'True'):
                        pass
                    else: 
                        ec2.create_tags(Resources=instance_ids,Tags=[{'Key':'scheduler:ec2-startstop','Value':'True'}])

Tags: 实例instancelambdakey函数in标记true
1条回答
网友
1楼 · 发布于 2024-04-26 00:23:17

AmazonEC2实例可以有多个标记

但是,只要代码找到不等于DoNotTerminate的标记,它就会创建标记,而不是只为每个实例添加一次标记

您应该移动代码,类似于:

def lambda_handler(event, context): 
    instance_to_tag = []
    for reservation in boto_response['Reservations']:  # Not sure where boto_response comes from!
        for instance in reservation['Instances']:
            if instance['State']['Name'] == 'running':

                # If there is no `DoNotTerminate` tag
                if not [tag for tag in instance['Tags'] if tag['Key'] == 'DoNotTerminate' and tag['Value'] == 'True']:
                    instance_to_tag.append(instance['InstanceId'])

    # Apply a tag to all instances found
    ec2.create_tags(Resources=instance_to_tag, Tags=[{'Key':'scheduler:ec2-startstop','Value':'True'}])

相关问题 更多 >