Python 如果ec2实例不存在,则在每个ec2实例上创建一个标记。使用新值更新标记(如果存在)

Python 如果ec2实例不存在,则在每个ec2实例上创建一个标记。使用新值更新标记(如果存在),python,amazon-web-services,amazon-ec2,tags,boto3,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

我正在尝试编写一个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'})

下面是一些应该执行此操作的代码:

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': ''}]
                )

你的问题是什么?它作为一个命令行Python程序(即,在Lambda之外,通过直接调用
处理程序
函数)对我起作用。您在CloudWatch日志中遇到了什么错误?“这不起作用”是什么意思?如果标签存在,我想更新标签值,如果不存在,则添加标签,然后添加标签。请参阅上面的“我的尝试”部分。您可以使用与创建标记完全相同的方式更新标记。只需创建它,它就会覆盖现有值。在上述代码中,遥控
标记
行和
if