Few of my critical EBS Volumes are being backed up as snapshots periodically. Is there any way I can setup a deletion policy by which ONLY the recent two snapshots are maintained?
For example: In one of the environment I have close to 300 snapshots from 10 EBS Volumes. Once I have this policy it should come down to 20 Snapshot and be maintained at that level.
Here's some code that snapshots ALL EBS volumes, then only keeps the latest 2 snapshots. You could also modify it to only snapshot volumes with a particular tag. Substitute your own Region as appropriate.
#!/usr/bin/env python
import boto.ec2, os
MAX_SNAPSHOTS = 2 # Number of snapshots to keep
# Connect to EC2 in this region
connection = boto.ec2.connect_to_region('ap-southeast-2')
# Get a list of all volumes
volumes = connection.get_all_volumes()
# Create a snapshot of each volume
for v in volumes:
connection.create_snapshot(v.id)
# Too many snapshots?
snapshots = v.snapshots()
if len(snapshots) > MAX_SNAPSHOTS:
# Delete oldest snapshots, but keep MAX_SNAPSHOTS available
snap_sorted = sorted([(s.id, s.start_time) for s in snapshots], key=lambda k: k[1])
for s in snap_sorted[:-MAX_SNAPSHOTS]:
print "Deleting snapshot", s[0]
connection.delete_snapshot(s[0])
Just run it as a daily cron
job.