I'm scheduled automatic creation EBS Snapshots using CloudWatch
How to schedule automatic deleting old snapshots?
Asked
Active
Viewed 862 times
0

Artik
- 153
- 4
- 14
2 Answers
2
This might be of help. It's a Python program I wrote that takes snapshots of all volumes and keeps the last 2 snapshots.
You could run a program like this on an EC2 instance, or convert it to run as a scheduled AWS Lambda function.
#!/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('<insert region here>')
# 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])

John Rotenstein
- 241,921
- 22
- 380
- 470
0
You can take snapshots and put tags like "DeleteOn:" on those snapshots.
Write another lambda which read snapshots on basis of this tag and delete it on that particular date. There is detailed on this in botocore Doc: https://botocore.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html

Taha
- 123
- 1
- 7