如果每个ec2实例不存在,请创建一个标签。使用新值更新标签(如果存在)

时间:2019-03-24 02:18:40

标签: python amazon-web-services amazon-ec2 tags boto3

我正在尝试编写一个lambda来创建键“ MyID”和值“ null”的标签。如果标签不存在,则标签应附加到每个实例。

import boto3
client = boto3.client('ec2')

def handler(event,context):
    response = client.describe_instances()
    for reservation in response['Reservations']:
        for instance in reservation['Instances']:
            instance.create_tags(Tags={'TagName': 'TagValue'})

1 个答案:

答案 0 :(得分:1)

这是一些应该执行的代码:

import boto3
client = boto3.client('ec2', region_name='ap-southeast-2')

def handler(event, context):

    # Get a list of instances
    response = client.describe_instances()

    # For each instance
    for reservation in response['Reservations']:
        for instance in reservation['Instances']:

            # Extract existing tags
            tags = [tag['Key'] for tag in instance['Tags']]

            if 'MyID' not in tags:
                # Add a tag
                tag_response = client.create_tags(
                    Resources=[instance['InstanceId']],
                    Tags=[{'Key': 'MyID', 'Value': ''}]
                )