-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSnapshotCreation.py
85 lines (69 loc) · 2.76 KB
/
SnapshotCreation.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import boto3
import os
import collections
import datetime
DefaultBackupRetentionDays = int(os.environ.get("DefaultBackupRetentionDays"))
ec = boto3.client('ec2')
def lambda_handler(event, context):
"""lambda_handler will execute the function in AWS Lambda."""
reservations = ec.describe_instances(
).get(
'Reservations', []
)
allinstances = sum(
[
[i for i in r['Instances']]
for r in reservations
], [])
print(f"Found {len(allinstances)} to consider for backing up")
backup_instances = []
to_tag = collections.defaultdict(list)
for instance in allinstances:
tags = instance["Tags"]
backups = [tag.get('Value') for tag in tags if tag.get('Key') == 'Backup']
backup = backups[0] if backups else None
if backup != 'False':
backup_instances.append(instance)
for instance in backup_instances:
print(f"Backin up {instance['InstanceId']}")
try:
retention_days = [
int(t.get('Value')) for t in instance['Tags']
if t['Key'] == 'Retention'][0]
except IndexError:
retention_days = DefaultBackupRetentionDays
for dev in instance['BlockDeviceMappings']:
if dev.get('Ebs', None) is None:
continue
vol_id = dev['Ebs']['VolumeId']
print(f"Found EBS Volume {vol_id} on instance {instance['InstanceId']}")
snap = ec.create_snapshot(
Description='Created By ebs-backups-SnapshotCreationFunction',
VolumeId=vol_id,
TagSpecifications=[
{
'ResourceType': 'snapshot',
'Tags': [
{
'Key': 'Name',
'Value': instance['InstanceId']
},
]
},
],
)
to_tag[retention_days].append(snap['SnapshotId'])
print(f"Retaining snapshot {snap['SnapshotId']} of volume {vol_id }from instance {instance['InstanceId']} for {retention_days} days")
for retention_days in list(to_tag.keys()):
delete_date = datetime.date.today() + datetime.timedelta(days=retention_days)
delete_fmt = delete_date.strftime('%Y-%m-%d')
print(f"Will delete {len(to_tag[retention_days])} snapshots on {delete_fmt}")
ec.create_tags(
Resources=to_tag[retention_days],
Tags=[
{'Key': 'DeleteOn', 'Value': delete_fmt},
{'Key': 'CreatedBy', 'Value': 'ebs-backups-SnapshotCreationFunction'},
]
)
if __name__ == '__main__':
lambda_handler(None, None)