Last active
April 15, 2020 08:57
-
-
Save duaraghav8/f19643f196c416c55cef0b013244d954 to your computer and use it in GitHub Desktop.
Cleanup old EBS snapshots and AMIs
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
# NOTE: This script is extremely destructive. Be sure to understand it before using. | |
# This Script deletes all old snapshots and AMIs from Amazon EBS. It only retains the latest snapshot and AMI for each volume whose snapshots exist. | |
# It has been tested with Python3 | |
import boto3 | |
# Fill this up or use sts.get_caller_identity() | |
AWS_ACCOUNT_ID = "" | |
ec2 = boto3.client("ec2") | |
volumes = {} | |
def delete_ami(snapshot_id): | |
res = ec2.describe_images(Filters=[ | |
{ | |
"Name": "owner-id", | |
"Values": [AWS_ACCOUNT_ID], | |
}, | |
{ | |
"Name": "block-device-mapping.snapshot-id", | |
"Values": [snapshot_id], | |
} | |
]) | |
for image in res["Images"]: | |
print(f"Deleting AMI {image['ImageId']}") | |
ec2.deregister_image(ImageId=image["ImageId"]) | |
# If you have more than 1K snapshots, you'll need to paginate. | |
res = ec2.describe_snapshots( | |
Filters=[{ | |
"Name": "owner-id", | |
"Values": [AWS_ACCOUNT_ID], | |
}] | |
) | |
for shot in res["Snapshots"]: | |
if shot["VolumeId"] not in volumes: | |
volumes[shot["VolumeId"]] = [] | |
volumes[shot["VolumeId"]].append({ | |
"volume-id": shot["VolumeId"], | |
"snapshot-id": shot["SnapshotId"], | |
"ts": shot["StartTime"] | |
}) | |
for v in volumes: | |
if len(volumes[v]) == 1: | |
continue | |
volumes[v].sort(key=lambda i: i["ts"], reverse=True) | |
volumes[v].pop(0) | |
print(f"{len(volumes[v])} snapshots of Volume {v} need to be deleted") | |
for item in volumes[v]: | |
delete_ami(item["snapshot-id"]) | |
print(f"Deleting {item['snapshot-id']}") | |
ec2.delete_snapshot(SnapshotId=item["snapshot-id"]) | |
print("===================================") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment