【问题标题】:Create a tag on each ec2 instance if it does not exist. Update tag with new value if it exists如果每个 ec2 实例不存在,请在其上创建一个标签。如果存在,则使用新值更新标签
【发布时间】:2019-03-24 02:18:39
【问题描述】:

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

【问题讨论】:

  • 你有什么问题?

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


【解决方案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': ''}]
                )

【讨论】:

  • 它对我来说是一个命令行 Python 程序(也就是说,在 Lambda 之外,通过直接调用 handler 函数)。您在 CloudWatch Logs 中遇到什么错误? “这不起作用”是什么意思?
  • 如果标签存在,我想更新标签值,如果标签不存在,我想添加标签,然后添加标签。请参阅上面的“我的尝试”部分。
  • 您可以按照与创建标签完全相同的方式更新标签。只需创建它,它将覆盖现有值。在上面的代码中,远程tags 线和if。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 2018-11-22
  • 2021-02-28
  • 2021-12-30
  • 2016-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多