· 9 years ago · Oct 24, 2016, 09:50 AM
1#Delete Snapshots Older than 7 days with "Automated backup from Lambda service" in the name
2import boto3
3from datetime import datetime, timedelta
4
5#Setup
6ACCESS_KEY=''
7SECRET_KEY=''
8ec2 = boto3.client('ec2', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name='eu-west-1')
9deletedCounter=0
10deletingOverDays=7
11
12#Older than 7days
13delete_time = datetime.utcnow() - timedelta(days=deletingOverDays)
14
15
16filters = [
17 {
18 'Name':'description',
19 'Values':['Automated backup from Lambda service*']
20 }
21]
22
23snapshots = ec2.describe_snapshots(Filters=filters)
24snapshots=snapshots["Snapshots"]
25for snapshot in snapshots:
26 start_time = datetime.strptime(
27 str(snapshot['StartTime']),
28 '%Y-%m-%d %H:%M:%S+00:00'
29 )
30 if start_time < delete_time:
31 deletedCounter=deletedCounter+1
32 snapId=snapshot['SnapshotId']
33 print('Deleting snapshot' + str(snapId))
34 ec2.delete_snapshot(SnapshotId=snapId)
35print (deletedCounter)
36
37
38
39##
40# 1) Put both olderThan, backupName, region-name as script argument, with default values hardcoded
41# 2) I don't know boto3 API, but put null checks to avoid your script to crash (ie. validate if snapshot object is null before using it, check if connection to aws was sucessful)
42# 3) Improve logs (things like "Starting script with olderThan=XX. Successfully connected to aws, deleting snapshot YY")
43# 4) Timestamp the executions
44# 5) Improve readability (suggestions: ec2client, deletedCount -> numberOfDeletedSnapshots, deletingOverDays -> numberOfDaysToDeleteFilesOlderThan, start_time -> snapshotStartTime, delete_time -> minSnapshotTimeToDelete, snapId -> snapshotId )
45# 6) Stay consistent with var names.