-
Notifications
You must be signed in to change notification settings - Fork 31
/
sam-template.yaml
474 lines (434 loc) · 15.8 KB
/
sam-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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
aws-lambda
WCIVF Template for aws-lambda
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 240
Parameters:
AppDjangoSettingsModule:
Description: "The DJANGO_SETTINGS_MODULE environment variable passed to the app."
Type: String
AppRdsHost:
Description: "The RDS_HOST environment variable passed to the app."
Type: String
AppRdsDbName:
Description: "The RDS_DB_NAME environment variable passed to the app."
Type: String
AppRdsDbPassword:
Description: "The DB_PASSWORD environment variable passed to the app."
Type: String
AppSentryDsn:
Description: "The SENTRY_DSN environment variable passed to the app."
Type: String
AppSecretKey:
Description: "The django SECRET_KEY environment variable passed to the app."
Type: String
AppDcEnvironment:
Description: "The DC_ENVIRONMENT environment variable passed to the app."
Type: String
VpcIdParameter:
Description: "VPC ID"
Type: String
SubnetIdsParameter:
Description: "List of subnet IDs"
Type: CommaDelimitedList
SSLCertificateArn:
Description: "SSL Certificate ARN"
Type: String
InstanceType:
Description: "The instance type to be used"
Type: String
Domain:
Description: "The domain to be used"
Type: String
AppSlackFeedbackWebhookUrl:
Description: "Webhook url used to send feeback entries to Slack"
Type: String
AppYnrApiKey:
Description: "API key used to import data from YNR"
Type: String
AppFeedbackDbEnabled:
Default: FEEDBACK_DB_ENABLED
Description: "Is the feedback DB enabled?"
Type: AWS::SSM::Parameter::Value<String>
AppFeedbackDbPassword:
Default: FEEDBACK_DB_PASSWORD
Description: "Webhook url used to send feeback entries to Slack"
Type: AWS::SSM::Parameter::Value<String>
AppFeedbackDbHost:
Default: FEEDBACK_DB_HOST
Description: "Webhook url used to send feeback entries to Slack"
Type: AWS::SSM::Parameter::Value<String>
Resources:
WCIVFControllerFunction:
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:
FunctionName: WCIVFControllerFunction
Role: !Sub "arn:aws:iam::${AWS::AccountId}:role/WCIVFLambdaExecutionRole"
CodeUri: .
Handler: wcivf.lambda_handler.handler
MemorySize: 256
Runtime: python3.12
Timeout: 360
Environment:
Variables:
DJANGO_SETTINGS_MODULE: !Ref AppDjangoSettingsModule
RDS_HOST: !Ref AppRdsHost
RDS_DB_NAME: !Ref AppRdsDbName
RDS_DB_PASSWORD: !Ref AppRdsDbPassword
SENTRY_DSN: !Ref AppSentryDsn
SECRET_KEY: !Ref AppSecretKey
DC_ENVIRONMENT: !Ref AppDcEnvironment
SLACK_FEEDBACK_WEBHOOK_URL: !Ref AppSlackFeedbackWebhookUrl
YNR_API_KEY: !Ref AppYnrApiKey
FEEDBACK_DB_ENABLED: !Ref AppFeedbackDbEnabled
FEEDBACK_DB_PASSWORD: !Ref AppFeedbackDbPassword
FEEDBACK_DB_HOST: !Ref AppFeedbackDbHost
Tags:
dc-environment: !Ref AppDcEnvironment
dc-product: wcivf
CreatedVia: CloudFormation
Events:
ImportPeopleRecentlyUpdated:
Type: Schedule # More info about API Event Source: https://github.com/aws/serverless-application-model/blob/master/versions/2016-10-31.md#schedule
Properties:
Schedule: cron(*/5 * ? * * *) # using the ? as you cannot use * wildcard for both day-of-month and day-of-week field. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html#CronExpressions
Name: import-people-recently-updated
Description: Update all people updated in YNR recently
Input: '{"command": "import_people", "args": ["--recently-updated"]}'
RetryPolicy:
MaximumRetryAttempts: 0
DeleteDeletedPeople:
Type: Schedule # More info about API Event Source: https://github.com/aws/serverless-application-model/blob/master/versions/2016-10-31.md#schedule
Properties:
Schedule: rate(1 hour)
Name: delete-deleted-people
Description: Deletes people deleted in YNR in the last hour
Input: '{"command": "delete_deleted_people"}'
RetryPolicy:
MaximumRetryAttempts: 0
ImportBallotsRecentlyUpdated:
Type: Schedule # More info about API Event Source: https://github.com/aws/serverless-application-model/blob/master/versions/2016-10-31.md#schedule
Properties:
Schedule: cron(2-57/5 * ? * * *) # using the ? as you cannot use * wildcard for both day-of-month and day-of-week field. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html#CronExpressions
Name: import-ballots-recently-updated
Description: Update all ballots updated in YNR recently
Input: '{"command": "import_ballots", "args": ["--recently-updated"]}'
RetryPolicy:
MaximumRetryAttempts: 0
ImportParties:
Type: Schedule
Properties:
Schedule: rate(1 day)
Name: import-parties
Description: Import parties
Input: '{"command": "import_parties"}'
RetryPolicy:
MaximumRetryAttempts: 0
ImportNationalParties:
Type: Schedule
Properties:
Schedule: rate(6 hours) # every 6 hours
Name: import-national-parties
Description: Import national parties
Input: '{"command": "import_national_parties"}'
RetryPolicy:
MaximumRetryAttempts: 0
BatchFeedbackToSlack:
Type: Schedule
Properties:
Schedule: cron(0 9 ? * FRI *) # using the ? as you cannot use * wildcard for both day-of-month and day-of-week field. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html#CronExpressions
Name: batch-feedback-to-slack
Description: Send feedback entries for the last week to slack
Input: '{"command": "batch_feedback_to_slack", "args": ["--hours=24"]}'
# ImportHustings:
# Type: Schedule
# Properties:
# Schedule: rate(1 hour)
# Name: import-hustings
# Description: Import hustings from google spreadsheets
# Input: '{"command": "import_hustings"}'
ImportLeaflets:
Type: Schedule
Properties:
Schedule: rate(1 hour)
Name: import-leaflets
Description: Import leaflets
Input: '{"command": "import_leaflets", "args": ["--recently-uploaded", "--uploaded-since=2024-05-22"]}'
ImportWikipediaBios:
Type: Schedule
Properties:
Schedule: cron(0 9 * * ? *)
Name: import-wikipedia-bios
Description: Import wikipedia bio extracts
Input: '{"command": "import_wikipedia_bios", "args": ["--current"]}'
RetryPolicy:
MaximumRetryAttempts: 0
# Import2024PPCs:
# Type: Schedule
# Properties:
# Schedule: rate(1 hour)
# Name: import-2024-ppcs
# Description: Import 2024 PPCs
# Input: '{"command": "import_2024_ppcs"}'
# RetryPolicy:
# MaximumRetryAttempts: 0
# ILPGlobal:
# Type: Schedule
# Properties:
# Schedule: rate(1 hour)
# Name: import-local-parties-global
# Description: Import LocalParty objects from google spreadsheets
# Input: '{"command": "import_local_parties", "args": ["--date=2023-5-2"]}'
WCIVFCodeDeployApp:
Type: AWS::CodeDeploy::Application
Properties:
ApplicationName: WCIVFCodeDeploy
ComputePlatform: Server
# cannot apply tags without recreating - applied in console
ElbHTTPSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: 'HTTP traffic'
GroupName: 'Elb Security Group'
SecurityGroupIngress:
- CidrIp: 0.0.0.0/0
FromPort: 80
IpProtocol: tcp
ToPort: 80
- CidrIp: 0.0.0.0/0
FromPort: 443
IpProtocol: tcp
ToPort: 443
VpcId: !Ref VpcIdParameter
Tags:
- Key: dc-environment
Value: !Ref AppDcEnvironment
- Key: dc-product
Value: wcivf
- Key: CreatedVia
Value: CloudFormation
InstanceHTTPSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: 'Allow HTTP and HTTPS access for an instance from the ALB security group'
GroupName: 'InstanceHTTPSecurityGroup'
SecurityGroupIngress:
- FromPort: 8000
IpProtocol: tcp
SourceSecurityGroupId: !Ref ElbHTTPSecurityGroup
ToPort: 8000
- FromPort: 80
IpProtocol: tcp
SourceSecurityGroupId: !Ref ElbHTTPSecurityGroup
ToPort: 80
- FromPort: 443
IpProtocol: tcp
SourceSecurityGroupId: !Ref ElbHTTPSecurityGroup
ToPort: 443
VpcId: !Ref VpcIdParameter
Tags:
- Key: dc-environment
Value: !Ref AppDcEnvironment
- Key: dc-product
Value: wcivf
- Key: CreatedVia
Value: CloudFormation
WCIVFTargetGroup:
Type: "AWS::ElasticLoadBalancingV2::TargetGroup"
Properties:
HealthCheckIntervalSeconds: 30
HealthCheckPath: "/_status_check/"
Port: 8000
Protocol: "HTTP"
HealthCheckPort: "traffic-port"
HealthCheckProtocol: "HTTP"
HealthCheckTimeoutSeconds: 5
UnhealthyThresholdCount: 5
TargetGroupAttributes:
- Key: deregistration_delay.timeout_seconds
Value: 30
TargetType: "instance"
Matcher:
HttpCode: "200"
HealthyThresholdCount: 2
VpcId: !Ref VpcIdParameter
Name: "wcivf-alb-tg"
HealthCheckEnabled: true
Tags:
- Key: dc-environment
Value: !Ref AppDcEnvironment
- Key: dc-product
Value: wcivf
- Key: CreatedVia
Value: CloudFormation
ApplicationLoadBalancer:
Type: "AWS::ElasticLoadBalancingV2::LoadBalancer"
Properties:
Name: "wcivf-alb"
Scheme: "internet-facing"
Type: "application"
SecurityGroups:
- !Ref ElbHTTPSecurityGroup
IpAddressType: "ipv4"
Subnets: !Ref SubnetIdsParameter
Tags:
- Key: dc-environment
Value: !Ref AppDcEnvironment
- Key: dc-product
Value: wcivf
- Key: CreatedVia
Value: CloudFormation
HTTPListener:
Type: "AWS::ElasticLoadBalancingV2::Listener"
Properties:
LoadBalancerArn: !Ref ApplicationLoadBalancer
Port: 80
Protocol: "HTTP"
DefaultActions:
- Order: 2
TargetGroupArn: !Ref WCIVFTargetGroup
Type: "forward"
WWWRedirectListenerRule:
Type: "AWS::ElasticLoadBalancingV2::ListenerRule"
Properties:
Actions:
- Type: redirect
RedirectConfig:
Host: !Ref Domain
Path: "/#{path}"
Port: 443
Protocol: HTTPS
Query: "#{query}"
StatusCode: HTTP_301
Conditions:
- Field: host-header
HostHeaderConfig:
Values:
- !Sub 'www.${Domain}'
ListenerArn: !Ref HTTPListener
Priority: 1
WCIVFLaunchTemplate:
Type: AWS::EC2::LaunchTemplate
Properties:
LaunchTemplateName: wcivf
LaunchTemplateData:
BlockDeviceMappings:
- DeviceName: /dev/sda1
Ebs:
VolumeSize: 35
VolumeType: gp2
DeleteOnTermination: true
NetworkInterfaces:
- DeviceIndex: 0
AssociatePublicIpAddress: true
Groups:
- !Ref InstanceHTTPSecurityGroup
# This is needed as it has permissions needed for the instance
# TODO create new role without packer permissions
IamInstanceProfile:
Name: 'CodeDeploy-EC2-Instance-Profile'
# output of
# https://eu-west-2.console.aws.amazon.com/imagebuilder/home?region=eu-west-2#/images/arn%3Aaws%3Aimagebuilder%3Aeu-west-2%3A732292556707%3Aimage%2Feeimage-ubuntu%2F0.0.35%2F2/details
ImageId: 'ami-0c8d319e3a044e7da'
InstanceType: !Ref InstanceType
MetadataOptions:
InstanceMetadataTags: enabled
HttpEndpoint: enabled
TagSpecifications:
- ResourceType: launch-template
Tags:
- Key: dc-environment
Value: !Ref AppDcEnvironment
- Key: dc-product
Value: wcivf
- Key: CreatedVia
Value: CloudFormation
CloudFrontDistribution:
Type: 'AWS::CloudFront::Distribution'
Properties:
DistributionConfig:
Comment: 'Cloudfront Distribution pointing to the ALB origin'
Origins:
- Id: Static
DomainName: !GetAtt ApplicationLoadBalancer.DNSName
CustomOriginConfig:
OriginProtocolPolicy: "http-only"
OriginCustomHeaders:
- HeaderName: X-Forwarded-Host
HeaderValue: !Ref Domain
- HeaderName: X-Forwarded-Proto
HeaderValue: https
OriginShield:
Enabled: true
OriginShieldRegion: eu-west-2
- Id: Dynamic
DomainName: !GetAtt ApplicationLoadBalancer.DNSName
CustomOriginConfig:
OriginProtocolPolicy: "http-only"
OriginCustomHeaders:
- HeaderName: X-Forwarded-Host
HeaderValue: !Ref Domain
- HeaderName: X-Forwarded-Proto
HeaderValue: https
Enabled: true
HttpVersion: 'http2'
Aliases:
- !Ref Domain
- !Sub "www.${Domain}"
PriceClass: "PriceClass_100"
ViewerCertificate:
AcmCertificateArn: !Ref SSLCertificateArn
MinimumProtocolVersion: TLSv1.1_2016
SslSupportMethod: sni-only
DefaultCacheBehavior:
AllowedMethods: [ GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE ]
TargetOriginId: Dynamic
ForwardedValues:
QueryString: true
Cookies:
Forward: "all"
Headers:
- Authorization
- Origin
- Referer
ViewerProtocolPolicy: "redirect-to-https"
CacheBehaviors:
- AllowedMethods: [ GET, HEAD, OPTIONS ]
PathPattern: static/*
TargetOriginId: Static
Compress: true
ForwardedValues:
QueryString: true
Cookies:
Forward: none
Headers:
- Authorization
- Origin
ViewerProtocolPolicy: "redirect-to-https"
MinTTL: '50'
DnsRecord:
Type: AWS::Route53::RecordSet
Properties:
AliasTarget:
DNSName: !GetAtt CloudFrontDistribution.DomainName
HostedZoneId: Z2FDTNDATAQYW2 # this is an AWS-owned, global singleton required for Aliases to CloudFront
HostedZoneName: !Sub "${Domain}."
Name: !Sub "${Domain}."
Type: A
WWWDnsRecord:
Type: AWS::Route53::RecordSet
Properties:
AliasTarget:
DNSName: !GetAtt CloudFrontDistribution.DomainName
HostedZoneId: Z2FDTNDATAQYW2 # this is an AWS-owned, global singleton required for Aliases to CloudFront
HostedZoneName: !Sub "${Domain}."
Name: !Sub "www.${Domain}."
Type: A
Outputs:
WCIVFControllerFunctionArn:
Description: "WCIVF Controller Lambda Function ARN"
Value: !GetAtt WCIVFControllerFunction.Arn