aaa
aaa

Reputation: 3

Create a tag on each ec2 instance if it does not exist. Update tag with new value if it exists

I am trying to write a lambda that creates a tag of key 'MyID' and value of 'null'. The tag should be attached to each instance if the tag does not exist.

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

Upvotes: 0

Views: 1860

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 270184

Here is some code that should do it:

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

Upvotes: 3

Related Questions