Curious
Curious

Reputation: 11

Lambda python - condition to tagging EC2 instance

I am trying to create EC2 tags in case of certain condition.

The Lambda function should tag an instance only if it has no tag (Key = 'DoNotTerminate', Value = 'True').

At the moment, the Lambda function is tagging every instance despite the condition.

I would thank for you help!

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

Upvotes: 0

Views: 979

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 269091

An Amazon EC2 instance can have multiple tags.

However, your code is creating tags whenever it finds a tag that is not equal to DoNotTerminate, rather than only adding tags once per instance.

You should move your code around, similar to:

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

Upvotes: 1

Related Questions