Created
May 11, 2017 15:32
-
-
Save michaelBenin/a1a4961b4077a080f330c62f5c04c88c to your computer and use it in GitHub Desktop.
Hold only the last two snapshots
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 | |
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