繁体   English   中英

Lambda python - 标记 EC2 实例的条件

[英]Lambda python - condition to tagging EC2 instance

我正在尝试在某些情况下创建 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'}])

一个 Amazon EC2 实例可以有多个标签。

但是,只要您的代码找到不等于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'}])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM