def lambda_handler()

in Lambda/Functions/TagEC2Dependencies/tag_ec2_dependencies.py [0:0]


def lambda_handler(event, context):
    # print("Received event: \n" + json.dumps(event))

    # If CreateTags failed nothing to do
    if 'errorCode' in event['detail']:
        print('CreateTags failed with error code {} and error message "{}", nothing to do.'
            .format(event['detail']['errorCode'], event['detail']['errorMessage']))
        return

    region = event['detail']['awsRegion']
    ec2 = boto3.client('ec2', region_name=region)

    instance_ids = []
    is_instance = re.compile('i-[0-9a-f]+')
    # Run instances may create several instances, then the event will contain 
    # several instances
    for item in event['detail']['requestParameters']['resourcesSet']['items']:
        if is_instance.match(item['resourceId']):
            instance_ids.append(item['resourceId'])
    
    # check if we were tagging any instances
    if len(instance_ids) == 0:
        return

    tags = []
    for tag in event['detail']['requestParameters']['tagSet']['items']:
        tags.append({
            'Key': tag['key'],
            'Value': tag['value']
        })

    # If the number of created instances then describe instances may be paginated
    paginator = ec2.get_paginator('describe_instances')
    instances_iterator = paginator.paginate(
        DryRun=False,
        InstanceIds=instance_ids
    )

    for page in instances_iterator:
        resources = []
        for reservation in page['Reservations']:
            for instance in reservation['Instances']:
                for eni in instance['NetworkInterfaces']:
                    resources.append(eni['NetworkInterfaceId'])

                for volume in instance['BlockDeviceMappings']:
                    if 'Ebs' in volume:
                        resources.append(volume['Ebs']['VolumeId'])

        print("Tagging resorces for instance ids:\n[{}]".format(', '.join(instance_ids)))
        print("Resources to be tagged:\n[{}]".format(', '.join(resources)))

        ec2.create_tags(
            DryRun=False,
            Resources=resources,
            Tags=tags
        )

    return