-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtemplate.yaml
443 lines (419 loc) · 14.8 KB
/
template.yaml
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
aws-newsletter-backend
Backend for subscribe email addresses for AWS Newsletter
Parameters:
EmailSender:
Default: '[email protected]'
Description: E-Mail Id from which the Mail will be send
Type: String
EmailWhitelistPattern:
Default: '(^[a-zA-Z0-9_.+-]+@reply\.(de|it|com|eu)$)'
Description: Regex to whitelist desired email domains
Type: String
MinLength: 26
MailFrequency:
Default: 'rate(7 days)'
Description: how often the email should be send
Type: String
CutoffDays:
Default: 7
Description: How old the feeds should be
Type: Number
MinValue: 1
MaxValue: 31
OpsEmailid:
Description: E-Mail Id for operational notifications
Type: String
AllowedPattern: '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
Resources:
SubscribeWebsiteBucket:
Type: 'AWS::S3::Bucket'
Properties:
BucketName: !Join [ "-", [ !Ref AWS::StackName, !Ref AWS::AccountId, !Ref AWS::Region] ]
WebsiteConfiguration:
ErrorDocument: 'index.html'
IndexDocument: 'index.html'
SubscribeWebsiteBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref SubscribeWebsiteBucket
PolicyDocument:
Version: 2012-10-17
Statement:
- Action:
- 's3:GetObject'
Effect: Allow
Resource: !Join
- ''
- - 'arn:aws:s3:::'
- !Ref SubscribeWebsiteBucket
- /*
Principal: '*'
NewsletterSNSTopic:
Type: AWS::SNS::Topic
Properties:
TopicName: "SNS_SUBSCRIBERS"
NewsletterSubscribersApi:
Type: AWS::Serverless::Api
Properties:
Cors:
AllowMethods: "'POST'"
AllowHeaders: "'*'"
AllowOrigin: "'*'"
MaxAge: "'600'"
StageName: prod
Tags:
application: newsletter
WebsiteUploaderLogGroup:
Type: AWS::Logs::LogGroup
DependsOn:
- WebsiteUploaderFunction
Properties:
LogGroupName: !Sub /aws/lambda/${WebsiteUploaderFunction}
RetentionInDays: 7
WebsiteUploaderFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: src/website_uploader/
Handler: app.lambda_handler
Runtime: python3.9
Timeout: 10
Environment:
Variables:
API_URL: !Sub "https://${NewsletterSubscribersApi}.execute-api.${AWS::Region}.amazonaws.com/prod/subscribe/"
WEBSITE_BUCKET: !Ref SubscribeWebsiteBucket
Architectures:
- arm64
Policies:
- AWSLambdaBasicExecutionRole # Managed Policy
- Version: '2012-10-17' # Policy Document
Statement:
- Effect: Allow
Action:
- s3:PutObject
- s3:PutObjectAcl
Resource: !Join ['', [!GetAtt SubscribeWebsiteBucket.Arn, "/*"]]
Tags:
application: newsletter
NewsletterSubscribersLogGroup:
Type: AWS::Logs::LogGroup
DependsOn:
- NewsletterSubscribersFunction
Properties:
LogGroupName: !Sub /aws/lambda/${NewsletterSubscribersFunction}
RetentionInDays: 3
NewsletterSubscribersFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: src/subscribe_backend/
Handler: app.lambda_handler
Runtime: python3.9
Timeout: 10
Environment:
Variables:
SNS_SUBSCRIBERS_ARN: !GetAtt NewsletterSNSTopic.TopicArn
EMAIL_WHITELIST_PATTERN: !Ref EmailWhitelistPattern
Architectures:
- arm64
Policies:
- AWSLambdaBasicExecutionRole # Managed Policy
- Version: '2012-10-17' # Policy Document
Statement:
- Effect: Allow
Action:
- sns:Subscribe
Resource: !GetAtt NewsletterSNSTopic.TopicArn
Events:
SubscribeEvent:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /subscribe
Method: post
RestApiId:
Ref: NewsletterSubscribersApi
Tags:
application: newsletter
NewsletterEmailLogGroup:
Type: AWS::Logs::LogGroup
DependsOn:
- NewsletterEmailFunction
Properties:
LogGroupName: !Sub /aws/lambda/${NewsletterEmailFunction}
RetentionInDays: 3
NewsletterEmailFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: src/newsletter_email/
Handler: newsletter.main
Layers:
- !Ref NewsletterEmailDepLayer
Runtime: python3.9
Timeout: 360
Environment:
Variables:
CUTOFF_DAYS: !Ref CutoffDays
EMAIL_SENDER: !Ref EmailSender
SNS_SUBSCRIBERS_ARN: !GetAtt NewsletterSNSTopic.TopicArn
Architectures:
- arm64
Policies:
- AWSLambdaBasicExecutionRole # Managed Policy
- Version: '2012-10-17' # Policy Document
Statement:
- Effect: Allow
Action:
- sns:ListSubscriptionsByTopic
Resource: !GetAtt NewsletterSNSTopic.TopicArn
- Effect: Allow
Action:
- ses:SendEmail
Resource: "*"
Events:
NewsLetterEmailer:
Type: Schedule
Properties:
Schedule: !Ref MailFrequency
Name: !Join ['-',[!Ref 'AWS::StackName', 'event']]
Enabled: True
Tags:
application: newsletter
NewsletterEmailDepLayer:
Type: AWS::Serverless::LayerVersion
Properties:
LayerName: newsletter-email-dependencies
ContentUri: src/newsletter_email/dependencies/
CompatibleRuntimes:
- python3.9
LicenseInfo: 'MIT'
RetentionPolicy: Retain
StackEventsHandler:
Type: Custom::stackeventshandler
Properties:
ServiceToken: !GetAtt StackEventsHandlerFunction.Arn
StackName: !Ref 'AWS::StackName'
LambdaFunctionName: !Ref WebsiteUploaderFunction
BucketName: !Ref SubscribeWebsiteBucket
StackEventsHandlerFunctionLogGroup:
Type: AWS::Logs::LogGroup
DependsOn:
- StackEventsHandlerFunction
Properties:
LogGroupName: !Sub /aws/lambda/${StackEventsHandlerFunction}
RetentionInDays: 3
StackEventsHandlerFunction:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile:
!Sub |
import boto3, logging
import cfnresponse
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info("event: {}".format(event))
try:
bucket = event['ResourceProperties']['BucketName']
lambdaFunctionName = event['ResourceProperties']['LambdaFunctionName']
if event['RequestType'] != 'Delete':
logger.info(f"lambdaFunctionName: {lambdaFunctionName}, event['RequestType']: {event['RequestType']}")
lambda_client = boto3.client('lambda')
response = lambda_client.invoke(
FunctionName=lambdaFunctionName,
)
logger.info(f"resonse: {response} from lambdaFunctionName: {lambdaFunctionName}")
if event['RequestType'] == 'Delete':
logger.info(f"bucket: {bucket}, event['RequestType']: {event['RequestType']}")
s3 = boto3.resource('s3')
bucket = s3.Bucket(bucket)
for obj in bucket.objects.filter():
logger.info("delete obj: {}".format(obj))
s3.Object(bucket.name, obj.key).delete()
sendResponseCfn(event, context, cfnresponse.SUCCESS)
except Exception as e:
logger.info("Exception: {}".format(e))
sendResponseCfn(event, context, cfnresponse.FAILED)
def sendResponseCfn(event, context, responseStatus):
responseData = {}
responseData['Data'] = {}
cfnresponse.send(event, context, responseStatus, responseData, "CustomResourcePhysicalID")
Handler: "index.lambda_handler"
Runtime: python3.9
MemorySize: 128
Timeout: 10
Role: !GetAtt StackEventsHandlerFunctionRole.Arn
StackEventsHandlerFunctionRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service:
- "lambda.amazonaws.com"
Action:
- "sts:AssumeRole"
Path: "/"
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: root
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: 'lambda:InvokeFunction'
Resource: !GetAtt WebsiteUploaderFunction.Arn
- Effect: "Allow"
Action:
- "s3:List*"
Resource: !Sub '${SubscribeWebsiteBucket.Arn}'
- Effect: "Allow"
Action:
- "s3:Delete*"
- "s3:List*"
- "s3:Get*"
Resource: !Sub '${SubscribeWebsiteBucket.Arn}/*'
NewsletterLambdaAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Join ['-',[!Ref 'AWS::StackName', 'alarm']]
AlarmDescription: "Alarm if lambda errors out too many times"
AlarmActions:
- !Ref NewsletterOpsTopic
Metrics:
- Id: m1
MetricStat:
Metric:
Dimensions:
- Name: "FunctionName"
Value: !Ref NewsletterSubscribersFunction
MetricName: Errors
Namespace: AWS/Lambda
Period: 300
Stat: Minimum
ReturnData: False
- Id: m2
MetricStat:
Metric:
Dimensions:
- Name: "FunctionName"
Value: !Ref NewsletterEmailFunction
MetricName: Errors
Namespace: AWS/Lambda
Period: 300
Stat: Minimum
ReturnData: False
- Id: expr1
Expression: IF(m1 OR m2, 1, 0)
Label: NewsletterBackendException
ComparisonOperator: "GreaterThanThreshold"
Threshold: 0
EvaluationPeriods: 1
NewsletterOpsTopic:
Type: AWS::SNS::Topic
Properties:
DisplayName: !Ref 'AWS::StackName'
TopicName: !Ref 'AWS::StackName'
Subscription:
- Protocol: email
Endpoint: !Ref OpsEmailid
NewsletterOpsTopicPolicy:
Type: 'AWS::SNS::TopicPolicy'
Properties:
Topics:
- !Ref NewsletterOpsTopic
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Sid: AllowCloudWatchEvents
Action: 'sns:Publish'
Resource: !Ref NewsletterOpsTopic
Principal:
Service: 'cloudwatch.amazonaws.com'
Condition:
StringEquals:
AWS:SourceOwner: !Ref 'AWS::AccountId'
DeploymentPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
ManagedPolicyName: !Join ['-',[!Ref 'AWS::StackName', 'cicd-deployment-policy']]
Description: Policy which can be used by a principal to deploy the newsletter solution
Path: /
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Sid: GeneralStatement
Action:
- "s3:Get*"
- "s3:CreateBucket"
- "s3:Describe*"
- "s3:Put*"
- "cloudformation:CreateChangeSet"
- "cloudformation:ExecuteChangeSet"
- "cloudformation:Describe*"
- "cloudformation:Get*"
Resource: "*"
- Effect: Allow
Sid: CW
Action:
- "cloudwatch:*"
Resource: !Sub "arn:aws:cloudwatch:${AWS::Region}:${AWS::AccountId}:alarm:${NewsletterLambdaAlarm}*"
- Effect: Allow
Sid: Events
Action:
- "events:*"
Resource:
- !Sub "arn:aws:events:${AWS::Region}:${AWS::AccountId}:rule/${AWS::StackName}-event*"
- !Sub "arn:aws:events:${AWS::Region}:${AWS::AccountId}:rule/newsletter-emailer"
- Effect: Allow
Sid: CloudFormation
Action:
- "cloudformation:*"
Resource: !Sub "arn:aws:cloudwatch:${AWS::Region}:${AWS::AccountId}:stack/${AWS::StackName}*"
- Effect: Allow
Sid: APIGateway
Action:
- "apigateway:POST"
- "apigateway:DELETE"
- "apigateway:PATCH"
- "apigateway:GET"
Resource:
- !Sub "arn:aws:apigateway:${AWS::Region}::/restapis"
- !Sub "arn:aws:apigateway:${AWS::Region}::/restapis/*"
- Effect: Allow
Sid: Logs
Action:
- "logs:*"
Resource: !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${AWS::StackName}-*"
- Effect: Allow
Sid: Iam
Action:
- "iam:*"
Resource: !Sub "arn:aws:iam::${AWS::AccountId}:role/${AWS::StackName}-*"
- Effect: Allow
Sid: SNS
Action:
- "sns:*"
Resource:
- !Sub "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:SNS_SUBSCRIBERS"
- !Sub "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:${AWS::StackName}"
- Effect: Allow
Sid: Lambda
Action:
- "lambda:*"
Resource:
- !Sub "arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${AWS::StackName}-*"
- !Sub "arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:layer:newsletter-email-*"
Outputs:
WebsiteBucket:
Description: "Website URL of the bucket to host the subscription form"
Value: !Join ['', [!GetAtt SubscribeWebsiteBucket.WebsiteURL, '/subscribe.html']]
DeploymentPolicy:
Description: "Least priviledge IAM policy for your CICD deployment user"
Value: !Ref DeploymentPolicy