Skip to content

Instantly share code, notes, and snippets.

@duaraghav8
Last active April 15, 2020 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duaraghav8/f19643f196c416c55cef0b013244d954 to your computer and use it in GitHub Desktop.
Save duaraghav8/f19643f196c416c55cef0b013244d954 to your computer and use it in GitHub Desktop.
Cleanup old EBS snapshots and AMIs
# 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