Skip to content

Instantly share code, notes, and snippets.

@rmrf-run
Created April 23, 2018 20:55
Show Gist options
  • Save rmrf-run/5467a47e2a283caa7d71e7f99e6bfd1e to your computer and use it in GitHub Desktop.
Save rmrf-run/5467a47e2a283caa7d71e7f99e6bfd1e to your computer and use it in GitHub Desktop.
Lambda function to update Volume tags with same tags from instance
import json
import boto3
'''
Works as Lambda function
Could pass in region from event or hardset region
'''
def main(event, context):
#print("Received event: " + json.dumps(event))
responseString = ''
region_list = ['ap-southeast-2']
for region in region_list:
print("Region: {}".format(region))
ec2 = boto3.resource('ec2', region_name=region)
for instance in ec2.instances.all():
print("Instance: {}".format(instance))
ec2tags = instance.tags
print("Tags: {}".format(ec2tags))
for volume in instance.volumes.all():
print("Volume: {}".format(volume))
if volume.tags != ec2tags:
print("Tags don't match, adding tags to volume")
for t in ec2tags:
# Skip any tags with aws: since those are reserved
if "aws:" in t['Key']:
print("Skipping: {} because reserved wording".format(t['Key']))
else:
volume.create_tags(
DryRun=False,
Tags=[
{
'Key': t['Key'],
'Value': t['Value']
},
]
)
responseString += 'Volume {} with tags {}.\n'.format(volume.id, ec2tags)
print("Volume Tags: {}".format(volume.tags))
responseString += 'Volume {} already has tags {}.\n'.format(volume.id, ec2tags)
return responseString
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment