-
-
Save dictcp/3b1dafbf8fd93bff7e174ae34b47f73d to your computer and use it in GitHub Desktop.
A lambda function that will copy EC2 tags to all related Volumes and Network Interfaces. A full writeup can be found on my site http://mlapida.com/thoughts/tagging-and-snapshotting-with-lambda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
def lambda_handler(event, context): | |
is_test = context.function_name == 'test' # this value is injected by SAM local | |
instances = boto3.resource('ec2').instances.all() | |
copyable_tag_keys = ["Team", "Billing", "BillingTag", "Env", "Project"] | |
for instance in instances: | |
copyable_tags = [t for t in instance.tags | |
if t["Key"] in copyable_tag_keys] if instance.tags else [] | |
if not copyable_tags: | |
continue | |
# Tag the EBS Volumes | |
print(f"{instance.instance_id}: {instance.tags}") | |
for vol in instance.volumes.all(): | |
print(f"{vol.attachments[0]['Device']}: {copyable_tags}") | |
if not is_test: | |
vol.create_tags(Tags=copyable_tags) | |
# Tag the Elastic Network Interfaces | |
for eni in instance.network_interfaces: | |
print(f"eth{str(eni.attachment['DeviceIndex'])}: {copyable_tags}") | |
if not is_test: | |
eni.create_tags(Tags=copyable_tags) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"Version": "2012-10-17", | |
"Statement": [ | |
{ | |
"Effect": "Allow", | |
"Action": [ | |
"logs:CreateLogGroup", | |
"logs:CreateLogStream", | |
"logs:PutLogEvents" | |
], | |
"Resource": "arn:aws:logs:*:*:*" | |
}, | |
{ | |
"Effect": "Allow", | |
"Action": [ | |
"ec2:DescribeInstances", | |
"ec2:DescribeVolumes", | |
"ec2:CreateTags" | |
], | |
"Resource": "*" | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment