Created
October 7, 2016 23:04
-
-
Save alexras/fe04e7addfae524707ea49f3867ef9a7 to your computer and use it in GitHub Desktop.
Name unnamed EBS snapshots after the image ID and device name to which they're mapped
This file contains hidden or 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
#!/usr/bin/env python | |
''' | |
The association between a snapshot and its corresponding AMI and device name is tedious to extract by hand. | |
This script names all snapshots "<AMI name> (<AMI id>) <device name>", which makes the associations much easier | |
to see. It also makes it easy to find "orphaned" snapshots, i.e. those that aren't associated with extant AMIs. | |
''' | |
import boto3 | |
# Your region and profile name will probably differ | |
session = boto3.Session(profile_name='production') | |
ec2_client = session.client('ec2', region_name='us-west-2') | |
regions = ec2_client.describe_regions()['Regions'] | |
for region in regions: | |
region_name = region['RegionName'] | |
ec2_client = session.client('ec2', region_name=region_name) | |
print 'Searching %s' % (region_name) | |
images = ec2_client.describe_images(Owners=['self'])['Images'] | |
for image in images: | |
for block_device_mapping in image['BlockDeviceMappings']: | |
if 'Ebs' in block_device_mapping and \ | |
'SnapshotId' in block_device_mapping['Ebs']: | |
snapshot_tag = "%s (%s) %s" % ( | |
image['Name'], | |
image['ImageId'], | |
block_device_mapping['DeviceName']) | |
snapshot_id = block_device_mapping['Ebs']['SnapshotId'] | |
print session.resource('ec2', region_name=region_name)\ | |
.Snapshot(snapshot_id).create_tags( | |
Tags=[{ | |
'Key': 'Name', | |
'Value': snapshot_tag | |
}]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment