-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathebs_snapshotter_lambda.json
193 lines (193 loc) · 8.88 KB
/
ebs_snapshotter_lambda.json
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "EBS Snapshot Runner for instances via Lambda.",
"Parameters": {
"LambdaIamRoleArn": {
"Type": "String",
"Description": "The ARN of the IAM role to run the lambda function as."
},
"TagKey": {
"Type": "String",
"Default": "Name",
"Description": "The Tag key to limit by"
},
"TagValue": {
"Type": "String",
"Default": "MyInstance",
"Description": "The Tag value to limit by"
}
},
"Resources": {
"EbsSnapshotWeeklyLambdaFunction": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Handler": "index.lambda_handler",
"Role": { "Ref": "LambdaIamRoleArn" },
"Runtime": "python2.7",
"Code": {
"ZipFile": {
"Fn::Join": ["\n", [
"import json",
"import boto3",
"def lambda_handler(event, context):",
" function_name=\"\"\"", { "Ref": "EbsSnapshotCreatorLambdaFunction" },"\"\"\"",
" client = boto3.client('lambda')",
" client.invoke(FunctionName=function_name.strip(), Payload=json.dumps({'retention_days': '42'}))"
]]
}
},
"Runtime": "python2.7",
"Timeout": 60
}
},
"EbsSnapshotDailyLambdaFunction": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Handler": "index.lambda_handler",
"Role": { "Ref": "LambdaIamRoleArn" },
"Runtime": "python2.7",
"Code": {
"ZipFile": {
"Fn::Join": ["\n", [
"import json",
"import boto3",
"def lambda_handler(event, context):",
" function_name=\"\"\"", { "Ref": "EbsSnapshotCreatorLambdaFunction" },"\"\"\"",
" client = boto3.client('lambda')",
" client.invoke(FunctionName=function_name.strip(), Payload=json.dumps({'retention_days': '7'}))"
]]
}
},
"Runtime": "python2.7",
"Timeout": 60
}
},
"EbsSnapshotJanitorLambdaFunction": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Handler": "index.lambda_handler",
"Role": { "Ref": "LambdaIamRoleArn" },
"Runtime": "python2.7",
"Code": {
"ZipFile": {
"Fn::Join": ["\n", [
"import boto3",
"import re",
"import datetime",
"ec = boto3.client('ec2')",
"iam = boto3.client('iam')",
"def lambda_handler(event, context):",
" account_ids = list()",
" try:",
" 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')",
" filters = [",
" {'Name': 'tag-key', 'Values': ['DeleteOn']},",
" {'Name': 'tag-value', 'Values': [delete_on]},",
" ]",
" snapshot_response = ec.describe_snapshots(OwnerIds=account_ids, Filters=filters)",
" for snap in snapshot_response['Snapshots']:",
" print \"Deleting snapshot %s\" % snap['SnapshotId']",
" ec.delete_snapshot(SnapshotId=snap['SnapshotId'])"
]]
}
},
"Runtime": "python2.7",
"Timeout": 60
}
},
"EbsSnapshotCreatorLambdaFunction": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Handler": "index.lambda_handler",
"Role": { "Ref": "LambdaIamRoleArn" },
"Runtime": "python2.7",
"Code": {
"ZipFile": {
"Fn::Join": ["\n", [
"import boto3",
"import collections",
"import datetime",
"ec = boto3.client('ec2')",
"def lambda_handler(event, context):",
" reservations = ec.describe_instances(",
" Filters=[",
" {'Name': 'tag-key', 'Values': [ { "Ref": "TagKey" } ]},",
" {'Name': 'tag-value', 'Values': [ { "Ref": "TagValue" } ]},",
" ]",
" ).get(",
" 'Reservations', []",
" )",
" instances = sum(",
" [",
" [i for i in r['Instances']]",
" for r in reservations",
" ], [])",
" print \"Found %d instances that need backing up\" % len(instances)",
" to_tag = collections.defaultdict(list)",
" for instance in instances:",
" try:",
" retention_days = int(event['retention_days'])",
" except Exception:",
" retention_days = 7",
" for dev in instance['BlockDeviceMappings']:",
" if dev.get('Ebs', None) is None:",
" continue",
" vol_id = dev['Ebs']['VolumeId']",
" print \"Found EBS volume %s on instance %s\" % (",
" vol_id, instance['InstanceId'])",
" snap = ec.create_snapshot(",
" VolumeId=vol_id,",
" )",
" to_tag[retention_days].append(snap['SnapshotId'])",
" print \"Retaining snapshot %s of volume %s from instance %s for %d days\" % (",
" snap['SnapshotId'],",
" vol_id,",
" instance['InstanceId'],",
" retention_days,",
" )",
" for retention_days in to_tag.keys():",
" delete_date = datetime.date.today() + datetime.timedelta(days=retention_days)",
" delete_fmt = delete_date.strftime('%Y-%m-%d')",
" print \"Will delete %d snapshots on %s\" % (len(to_tag[retention_days]), delete_fmt)",
" ec.create_tags(",
" Resources=to_tag[retention_days],",
" Tags=[",
" {'Key': 'DeleteOn', 'Value': delete_fmt},",
" {'Key': { "Ref": "TagKey" }, 'Value': { "Ref": "TagValue" }},",
" ]",
" )"
]]
}
},
"Runtime": "python2.7",
"Timeout": 60
}
}
},
"Outputs": {
"SnapshotTask": {
"Value": {
"Ref": "EbsSnapshotCreatorLambdaFunction"
}
},
"DailySnapshotTask": {
"Value": {
"Ref": "EbsSnapshotDailyLambdaFunction"
}
},
"WeeklySnapshotTask": {
"Value": {
"Ref": "EbsSnapshotWeeklyLambdaFunction"
}
},
"DeleteSnapshotTask": {
"Value": {
"Ref": "EbsSnapshotJanitorLambdaFunction"
}
}
}
}