Skip to content

Instantly share code, notes, and snippets.

@kjoconnor
Created November 6, 2013 21:33
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save kjoconnor/7344485 to your computer and use it in GitHub Desktop.
Save kjoconnor/7344485 to your computer and use it in GitHub Desktop.
boto script to delete snapshots matching a filter and older than X days
import sys
from boto.ec2 import connect_to_region
from datetime import datetime, timedelta
try:
days = int(sys.argv[1])
except IndexError:
days = 7
delete_time = datetime.utcnow() - timedelta(days=days)
filters = {
'tag-key': 'mybackups'
}
print 'Deleting any snapshots older than {days} days'.format(days=days)
ec2 = connect_to_region('us-west-1')
snapshots = ec2.get_all_snapshots(filters=filters)
deletion_counter = 0
size_counter = 0
for snapshot in snapshots:
start_time = datetime.strptime(
snapshot.start_time,
'%Y-%m-%dT%H:%M:%S.000Z'
)
if start_time < delete_time:
print 'Deleting {id}'.format(id=snapshot.id)
deletion_counter = deletion_counter + 1
size_counter = size_counter + snapshot.volume_size
# Just to make sure you're reading!
snapshot.delete(dry_run=True)
print 'Deleted {number} snapshots totalling {size} GB'.format(
number=deletion_counter,
size=size_counter
)
@raakey
Copy link

raakey commented May 16, 2017

Syntax error in module 'lambda_function': invalid syntax (lambda_function.py, line 17)

Getting error while executing in Lambda.
print 'Deleting any snapshots older than {days} days'.format(days=days)

@skumar3h
Copy link

skumar3h commented Jan 8, 2018

thanks. How can I use this script delete old snapshots except last two?

@Sagayaanitta
Copy link

This is helpful. How can we do this for RDS manual snapshots with for each loop for all regions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment