-
Notifications
You must be signed in to change notification settings - Fork 5
/
6-Base-SetWeight.yml
416 lines (384 loc) · 15.4 KB
/
6-Base-SetWeight.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
---
AWSTemplateFormatVersion: "2010-09-09"
Description: SetWeight functionality for VPN. Must be deployed in the SES region. Need to manually activate SES Receiving RuleSet after creation. 1) Lightsail sends alert to admin@ALERT_FROM_DOMAIN 2) Prereq - Set up forwarding for Lightsail alerts from admin@ALERT_FROM_DOMAIN to lightsail@ALERT_TO_DOMAIN. 3) Prereq - ALERT_TO_DOMAIN needs to be set up for SES Email Receiving 4) SES Email Receiving rule triggers SNS topic to trigger Lambda. Note we cannot call Lambda directly from SES because it does not attach the full email alert.
Parameters:
Environment:
Type: String
Description: Name of the environment.
HostedZoneId:
Type: String
SourceId:
Type: String
BatchId:
Type: String
VpnDomain:
Type: String
AlertFromDomain:
Type: String
Description: Probably same as VPN_DOMAIN, but not always
AlertToDomain:
Type: String
Resources:
SetWeightFunction:
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}';
const ALERT_FROM_DOMAIN = '${AlertFromDomain}';
exports.handler = function(event, context) {
console.log("event:\n", JSON.stringify(event));
// Grab the email notification, parse it
var snsMessage = event.Records[0].Sns.Message;
var sesNotification = JSON.parse(snsMessage);
console.log("parsed:\n", JSON.stringify(sesNotification, null, 2));
console.log('ensure valid source for email');
if (sesNotification.mail.source.endsWith("@" + ALERT_FROM_DOMAIN) !== true) {
console.log("Invalid email source");
context.fail("Invalid source for email: " + sesNotification.mail.source);
return;
}
// Check if any spam check failed
console.log('Check for Spam');
if (sesNotification.receipt.spfVerdict.status === 'FAIL'
|| sesNotification.receipt.dkimVerdict.status !== 'PASS'
|| sesNotification.receipt.spamVerdict.status !== 'PASS'
|| sesNotification.receipt.virusVerdict.status !== 'PASS'
|| sesNotification.receipt.dmarcVerdict.status === 'FAIL') {
console.log('Dropping spam/unverified');
context.fail("Spam/unverified message");
}
else {
// Not Failed, print body of email
var content = Buffer.from(sesNotification.content.toString('utf8'), 'base64').toString('ascii');
console.log("Not Spam - Email content:\n", content);
// find line with MonitoredResourceName: us-east-1-VPN-1A
var lines = content.split("\n");
for (var i = 0; i < lines.length; i++) {
if (lines[i].includes("MonitoredResourceName: ")) {
console.log("found: ", lines[i]);
// extract instance ID - last item
var lineSplit = lines[i].split(" ");
var instanceID = lineSplit[lineSplit.length - 1].trim(); // trim line breaks/whitespace
console.log(instanceID);
// transform ap-southeast-2-VPN-1A to ap-sydney
// 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 SetWeightFunctionRole.Arn
Runtime: nodejs14.x
Timeout: 20
SetWeightFunctionRole:
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
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}
SetWeightFromSnsPermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt SetWeightFunction.Arn
Action: lambda:InvokeFunction
Principal: !Sub sns.amazonaws.com
SourceArn: !Ref SetWeightSnsTopic
SetWeightSnsTopic:
Type: AWS::SNS::Topic
Properties:
Subscription:
- Endpoint: !GetAtt SetWeightFunction.Arn
Protocol: lambda
SetWeightSnsTopicPolicy:
Type: AWS::SNS::TopicPolicy
Properties:
PolicyDocument:
Version: '2008-10-17'
Statement:
- Effect: Allow
Principal:
AWS: "*"
Action:
- SNS:GetTopicAttributes
- SNS:SetTopicAttributes
- SNS:Subscribe
- SNS:ListSubscriptionsByTopic
- SNS:Publish
- SNS:Receive
Resource: !Ref SetWeightSnsTopic
Condition:
StringEquals:
AWS:SourceOwner: !Sub ${AWS::AccountId}
Topics:
- !Ref SetWeightSnsTopic
ReceiveRuleSet:
Type: AWS::SES::ReceiptRuleSet
Properties:
RuleSetName: !Ref AlertToDomain
ReceiveRule:
Type: AWS::SES::ReceiptRule
DependsOn:
- ReceiveRuleSet
- EmailsBucketPolicy
Properties:
RuleSetName: !Ref AlertToDomain
Rule:
Actions:
- S3Action:
BucketName: !Ref EmailsBucket
- SNSAction:
Encoding: Base64
TopicArn: !Ref SetWeightSnsTopic
Enabled: true
Recipients:
- !Sub lightsail@${AlertToDomain}
ScanEnabled: true
TlsPolicy: Require
SetWeightLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub /aws/lambda/${SetWeightFunction}
SetWeightEmailerErrorSubscriptionFilter:
Type: AWS::Logs::SubscriptionFilter
Properties:
DestinationArn:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, ErrorEmailerFunctionArn ] ]
FilterPattern: 'ERROR'
LogGroupName: !Ref SetWeightLogGroup
SetWeightEmailerSuccessSubscriptionFilter:
Type: AWS::Logs::SubscriptionFilter
Properties:
DestinationArn: !GetAtt SuccessEmailerFunction.Arn
FilterPattern: 'SUCCESS'
LogGroupName: !Ref SetWeightLogGroup
# ===== 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] 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'
EmailsBucket:
Type: AWS::S3::Bucket
DeletionPolicy: Retain
Properties:
AccessControl: Private
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
EmailsBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref EmailsBucket
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: AllowSESPuts
Effect: Allow
Principal:
Service: ses.amazonaws.com
Action: s3:PutObject
Resource: !Join
- ''
- - 'arn:aws:s3:::'
- !Ref EmailsBucket
- /*
Condition:
StringEquals:
aws:Referer: !Ref "AWS::AccountId"