-
-
Save coingraham/a715946c8297d7b95628d100be13eadc to your computer and use it in GitHub Desktop.
boto script to delete snapshots matching a filter and older than X days
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
import sys | |
import boto3 | |
from botocore.exceptions import ClientError | |
from datetime import datetime, timedelta | |
import time | |
import pytz | |
profile = "my_profile" | |
region = "us-west-2" | |
dry_run = True | |
tag_name = "Environment" | |
tag_value = "DEV" | |
session = boto3.session.Session(profile_name=profile, region_name=region) | |
ec2_client = session.client("ec2") | |
try: | |
days = int(sys.argv[1]) | |
except IndexError: | |
days = 7 | |
delete_time = datetime.now(pytz.utc) - timedelta(days=days) | |
print "Deleting any snapshots older than {days} days".format(days=days) | |
def iterate_and_delete(my_snapshot_iterator): | |
my_deletion_counter = 0 | |
my_size_counter = 0 | |
count = 1 | |
for snapshot in my_snapshot_iterator: | |
start_time = snapshot["StartTime"] | |
if start_time < delete_time: | |
my_deletion_counter = my_deletion_counter + 1 | |
my_size_counter = my_size_counter + snapshot["VolumeSize"] | |
# Just to make sure you're reading! | |
try: | |
print ec2_client.delete_snapshot( | |
SnapshotId=snapshot["SnapshotId"], | |
DryRun=dry_run | |
) | |
print "Deleting {}".format(snapshot["SnapshotId"]) | |
except ClientError as e: | |
if e.response['Error']['Code'] == 'DryRunOperation': | |
print "You would have deleted {}".format(snapshot["SnapshotId"]) | |
else: | |
print "Unexpected error: {}".format(e) | |
# Had to add this for deleting thousands of snapshosts | |
if count % 50 == 0: | |
print "Taking a break." | |
time.sleep(5) | |
count += 1 | |
return my_deletion_counter, my_size_counter | |
if __name__ == '__main__': | |
next_token = "" | |
deletion_counter = 0 | |
size_counter = 0 | |
snapshot_iterator = ec2_client.describe_snapshots( | |
Filters=[ | |
{ | |
"Name": "tag:{}".format(tag_name), | |
"Values": [ | |
tag_value, | |
] | |
}, | |
{ | |
"Name": "description", | |
"Values": [ | |
"Runaway Backup Jobs*", | |
] | |
}, | |
], | |
OwnerIds=["self"], | |
) | |
deleted, size = iterate_and_delete(snapshot_iterator["Snapshots"]) | |
deletion_counter += deleted | |
size_counter += size | |
if dry_run: | |
print "You would have deleted {number} snapshots totalling {size} GB".format( | |
number=deletion_counter, | |
size=size_counter) | |
else: | |
print "Deleted {number} snapshots totalling {size} GB".format( | |
number=deletion_counter, | |
size=size_counter) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment