-
Notifications
You must be signed in to change notification settings - Fork 5
/
7-StackSet-SetWeightFromHealth.yml
317 lines (295 loc) · 11.3 KB
/
7-StackSet-SetWeightFromHealth.yml
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
---
AWSTemplateFormatVersion: "2010-09-09"
Description: SetWeightFromHealth functionality for VPN. Differs from SetWeight because these are instance retirement/failure messages from AWS Health.
Parameters:
Environment:
Type: String
Description: Name of the environment.
HostedZoneId:
Type: String
SourceId:
Type: String
BatchId:
Type: String
VpnDomain:
Type: String
Resources:
SetWeightFromHealthFunction:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: !Sub >
const HOSTED_ZONE_ID = '${HostedZoneId}';
const SOURCE_ID = '${SourceId}';
const BATCH_ID = '${BatchId}';
const VPN_DOMAIN = '${VpnDomain}';
exports.handler = function(event, context) {
console.log("event received:\n", JSON.stringify(event));
if (!event) {
console.log("Event is null, aborting");
context.fail("Event is null, aborting");
return;
}
if (!event.includes("-VPN-")) {
console.log("Event does not contain -VPN-, aborting");
context.fail("Event does not contain -VPN-, aborting: " + JSON.stringify(event));
return;
}
// need to account for both ARN format and non ARN format
// example lightsail ARN: arn:aws:lightsail:us-east-2:123456789101:Instance/us-east-1-VPN-55A
// split by slash, take the last item
var eventSplit = event.split("/");
console.log("split:\n", JSON.stringify(eventSplit));
var instanceID = eventSplit[eventSplit.length - 1]
console.log("instance name:\n", instanceID)
// get the route 53 region name from instance ID so we can look it up
// e.g, ap-south-1-VPN-5a ==> ap-mumbai
// we want this to filter down Record name for Route 53
var splitInstanceID = instanceID.split("-VPN-");
var instanceIDregion = splitInstanceID[0]; // "ap-southeast-2"
var instanceRegion = "us-east";
switch(instanceIDregion) {
case 'ap-south-1':
instanceRegion = "ap-mumbai";
break;
case 'ap-northeast-2':
instanceRegion = "ap-seoul";
break;
case 'ap-southeast-1':
instanceRegion = "ap-singapore";
break;
case 'ap-southeast-2':
instanceRegion = "ap-sydney";
break;
case 'ap-northeast-1':
instanceRegion = "ap-tokyo";
break;
case 'ca-central-1':
instanceRegion = "canada";
break;
case 'eu-central-1':
instanceRegion = "eu-frankfurt";
break;
case 'eu-west-1':
instanceRegion = "eu-ireland";
break;
case 'eu-west-2':
instanceRegion = "eu-london";
break;
case 'eu-west-3':
instanceRegion = "eu-paris";
break;
case 'us-east-1':
instanceRegion = "us-east";
break;
case 'us-west-2':
instanceRegion = "us-west";
break;
default:
break;
}
// attach source ID
var recordName = instanceRegion + "-" + SOURCE_ID + "-" + BATCH_ID + "." + VPN_DOMAIN;
// look up instance ID on R53
var AWS = require('aws-sdk');
var route53 = new AWS.Route53();
var params = {
HostedZoneId: HOSTED_ZONE_ID,
MaxItems: '200',
StartRecordName: recordName,
StartRecordType: 'A'
};
console.log(params);
route53.listResourceRecordSets(params, function(err, data) {
if (err) {
// TODO: send error email on this and other errors
console.log(err, err.stack);
context.fail("Failed to list resource records:\n " + JSON.stringify(err));
return;
}
else {
console.log(data);
var records = data.ResourceRecordSets;
for (var j = 0; j < records.length; j++) {
// find the matching setIdentifier
if (records[j].SetIdentifier == instanceID) {
console.log("found entry: ", records[j]);
var record = records[j];
record.Weight = 0;
console.log("new record: ", record);
var params = {
ChangeBatch: {
Changes: [{
Action: "UPSERT",
ResourceRecordSet: record
}]
},
HostedZoneId: HOSTED_ZONE_ID
};
route53.changeResourceRecordSets(params, function(err, data) {
if (err) {
console.log(err, err.stack);
context.fail("error changing weight:\n" + JSON.stringify(err));
return;
}
else {
console.log(data);
console.log("SUCCESS Changed Weight for " + instanceID)
context.succeed();
return;
}
});
break; // don't do any others after the first match
}
}
}
});
};
Handler: index.handler
Role: !GetAtt SetWeightFromHealthFunctionRole.Arn
Runtime: nodejs14.x
Timeout: 20
SetWeightFromHealthFunctionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: lambda-logs-and-r53-health
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*:log-stream:*
- Effect: Allow
Action:
- route53:ChangeResourceRecordSets
- route53:ListResourceRecordSets
Resource:
- !Sub arn:aws:route53:::hostedzone/${HostedZoneId}
SetWeightFromHealthLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub /aws/lambda/${SetWeightFromHealthFunction}
SetWeightFromHealthEmailerErrorSubscriptionFilter:
Type: AWS::Logs::SubscriptionFilter
Properties:
DestinationArn:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, ErrorEmailerFunctionArn ] ]
FilterPattern: 'ERROR'
LogGroupName: !Ref SetWeightFromHealthLogGroup
SetWeightFromHealthEmailerSuccessSubscriptionFilter:
Type: AWS::Logs::SubscriptionFilter
Properties:
DestinationArn: !GetAtt SuccessEmailerFunction.Arn
FilterPattern: 'SUCCESS'
LogGroupName: !Ref SetWeightFromHealthLogGroup
# ===== Alerts =====
SuccessEmailerFunction:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: !Sub
- >
var aws = require('aws-sdk');
var zlib = require('zlib');
exports.handler = function(event, context) {
var payload = new Buffer(event.awslogs.data, 'base64');
zlib.gunzip(payload, function(e, result) {
if (e) { context.fail(e); }
else {
result = JSON.parse(result.toString('ascii'));
var sns = new aws.SNS();
var params = {
Message: JSON.stringify(result, null, 2),
Subject: "[SUCCESS-Health] Set Weight to 0",
TopicArn: "${CloudWatchAlarmEmailerTopic}"
};
sns.publish(params, context.done);
}
});
};
- CloudWatchAlarmEmailerTopic:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, CloudWatchAlarmEmailerTopic ] ]
Handler: index.handler
Role: !GetAtt SuccessEmailerFunctionRole.Arn
Runtime: nodejs12.x
Timeout: 10
SuccessEmailerFunctionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: lambda-logs-SNS-success
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*:log-stream:*
- Effect: Allow
Action:
- sns:Publish
Resource:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, CloudWatchAlarmEmailerTopic ] ]
SuccessEmailerCloudWatchPermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt SuccessEmailerFunction.Arn
Action: lambda:InvokeFunction
Principal: !Sub logs.${AWS::Region}.amazonaws.com
SourceAccount: !Ref 'AWS::AccountId'
HealthEventToSetWeightFromHealthRule:
Type: AWS::Events::Rule
Properties:
EventPattern:
source:
- aws.health
detail-type:
- "AWS Health Event"
Targets:
- Arn: !GetAtt SetWeightFromHealthFunction.Arn
Id: !Sub ${Environment}-${AWS::Region}-SetWeightFromHealthRule
InputTransformer:
InputPathsMap:
"firstResource" : "$.resources[0]"
InputTemplate: |
"<firstResource>"
PermissionForEventsToInvokeLambda:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref SetWeightFromHealthFunction
Action: "lambda:InvokeFunction"
Principal: "events.amazonaws.com"
SourceArn: !GetAtt HealthEventToSetWeightFromHealthRule.Arn