Quantcast
Channel: Active questions tagged amazon-ec2 - Stack Overflow
Viewing all articles
Browse latest Browse all 29259

Implement Auto Tagging for EC2 and its associated resources in boto3

$
0
0

A newbie to boto3, we have a requirement to implement specific tags to all resources in AWS, I would like to start with EC2. My requirement is to apply specific tags to EC2 and its resources (ENI, volume, EIP..) when we create a Name tag with specific Value to an EC2 instance. I did create a Lambda function and configured a trigger "CreateTags." I am sort of able to come to a stage where I could filer the instance which I am trying to create a Name tag, but lost on how to query Name and tag with a specific Value and assign specific tags to it and its resources, need help.

import json

import boto3

ec2 = boto3.resource('ec2')

def lambda_handler(event, context):
    print('Event: ' + str(event))
    print(json.dumps(event))

    # Contain all the identifiers of EC2 resources founds in a given event.
    # IDs could be EC2 instances, EBS Volumes, EBS snapshots, ENIs, or AMIs.
    ids =[]

    try:
        region = event['region']
        detail = event['detail']
        eventname = detail['eventName']

        print('region: ' + region)
        print('eventName: ' + eventname)
        print('detail: ' + str(detail))

        if not detail['responseElements']:
            print('No responseElements found')
            if detail['errorCode']:
                print('errorCode: ' + detail['errorCode'])
            if detail['errorMessage']:
                print('errorMessage: ' + detail['errorMessage'])
            return False

        if eventname == 'CreateTags':
            items = detail['responseElements']['instancesSet']['items']
            for item in items:
                ids.append(item['instanceId'])
            print(ids)
            print('number of instances: ' + str(len(ids)))

            base = ec2.instances.filter(InstanceIds=ids)

            #loop through the instances
            for instance in base:
                for vol in instance.volumes.all():
                    ids.append(vol.id)
                for eni in instance.network_interfaces:
                    ids.append(eni.id)
        else:
            print('Not supported action')

        if 'Tags' in ids:
            for tags in ids['Tags']:
                if tags["Key"] == 'Name':
                    tag_value = tag["prod-app*"]
                    print('Tagging resource' + resourceid)
                    ec2.create_tags(Resources=ids, Tags=[
                        {'Key': 'Product', 'Value': 'trial1'},
                        {'Key': 'Compliance', 'Value': 'trial2'}])

        print('Done tagging.')

        return True
    except Exception as e:
        print('Something Went wrong: ' + str(e))
        return False

Viewing all articles
Browse latest Browse all 29259

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>