Last active
February 16, 2022 17:54
-
-
Save nmagee/ff6597e796ed9a78a56faf756ac1e8ef to your computer and use it in GitHub Desktop.
Delete older EBS snapshots using `boto3`
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
#!/usr/bin/env python | |
##### THIS IS A DESTRUCTIVE SCRIPT - USE WITH CAUTION OR SET DryRun=True | |
import datetime | |
import sys | |
import boto3 | |
# Set these two variables before running: | |
age = 90 # Days to retain | |
dryrun = False # Set whether to actually delete or not [True|False] | |
aws_profile_name = 'uvarc' | |
def days_old(date): | |
date_obj = date.replace(tzinfo=None) | |
diff = datetime.datetime.now() - date_obj | |
return diff.days | |
boto3.setup_default_session(profile_name = aws_profile_name) | |
ec2 = boto3.client('ec2') | |
amis = ec2.describe_snapshots(OwnerIds=[ | |
'self' | |
]) | |
# ], MaxResults=90000) | |
for ami in amis['Snapshots']: | |
create_date = ami['StartTime'] | |
snapshot_id = ami['SnapshotId'] | |
day_old = days_old(create_date) | |
if day_old > age: | |
try: | |
print("deleting -> " + snapshot_id + " as image is " + str(day_old) + " old.") | |
# delete the snapshot | |
ec2.delete_snapshot(SnapshotId=snapshot_id,DryRun=dryrun) | |
except: | |
print("can't delete " + snapshot_id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment