-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathebs-snapshot-manager.py
53 lines (46 loc) · 1.82 KB
/
ebs-snapshot-manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import boto3
import re
import datetime
ec = boto3.client('ec2')
iam = boto3.client('iam')
"""
This function looks at *all* snapshots that have a "DeleteOn" tag containing
the current day formatted as YYYY-MM-DD. This function should be run at least
daily.
"""
def lambda_handler(event, context):
account_ids = list()
try:
"""
You can replace this try/except by filling in `account_ids` yourself.
Get your account ID with:
> import boto3
> iam = boto3.client('iam')
> print iam.get_user()['User']['Arn'].split(':')[4]
"""
iam.get_user()
except Exception as e:
# use the exception message to get the account ID the function executes under
account_ids.append(re.search(r'(arn:aws:sts::)([0-9]+)', str(e)).groups()[1])
delete_on = datetime.date.today().strftime('%Y-%m-%d')
# limit snapshots to process to ones marked for deletion on this day
# AND limit snapshots to process to ones that are automated only
# AND exclude automated snapshots marked for permanent retention
filters = [
{ 'Name': 'tag:DeleteOn', 'Values': [delete_on] },
{ 'Name': 'tag:Type', 'Values': ['Automated'] },
]
snapshot_response = ec.describe_snapshots(OwnerIds=account_ids, Filters=filters)
for snap in snapshot_response['Snapshots']:
for tag in snap['Tags']:
if tag['Key'] != 'KeepForever':
skipping_this_one = False
continue
else:
skipping_this_one = True
if skipping_this_one == True:
print "Skipping snapshot %s (marked KeepForever)" % snap['SnapshotId']
# do nothing else
else:
print "Deleting snapshot %s" % snap['SnapshotId']
ec.delete_snapshot(SnapshotId=snap['SnapshotId'])