Skip to content

Instantly share code, notes, and snippets.

@michaelBenin
Created May 11, 2017 15:32
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 michaelBenin/a1a4961b4077a080f330c62f5c04c88c to your computer and use it in GitHub Desktop.
Save michaelBenin/a1a4961b4077a080f330c62f5c04c88c to your computer and use it in GitHub Desktop.
Hold only the last two snapshots
#!/usr/bin/env python
import boto3
MAX_SNAPSHOTS = 2 # Number of snapshots to keep
# Create the EC2 resource
ec2 = boto3.resource('ec2')
# Get a list of all volumes
volume_iterator = ec2.volumes.all()
# Create a snapshot of each volume
for v in volume_iterator:
v.create_snapshot()
# Too many snapshots?
snapshots = list(v.snapshots.all())
if len(snapshots) > MAX_SNAPSHOTS:
# Delete oldest snapshots, but keep MAX_SNAPSHOTS available
snap_sorted = sorted([(s.id, s.start_time, s) for s in snapshots], key=lambda k: k[1])
for s in snap_sorted[:-MAX_SNAPSHOTS]:
print "Deleting snapshot", s[0]
s[2].delete()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment