-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipeline.yml
860 lines (819 loc) · 28.8 KB
/
pipeline.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
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
AWSTemplateFormatVersion: 2010-09-09
Description: CloudFront and Continuous Deployment setup for ill service stack
# Name:
# Recommended: ill-cloudfront-and-pipeline
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: Git Settings
Parameters:
- GitHubRepo
- GitHubBranch
- Label:
default: Pipeline approval
Parameters:
- PipelineApprovalAction
- PipelineApprovalEmail
- Label:
default: Alert Configuration
Parameters:
- AlertTopicArn
- Label:
default: Domain settings
Parameters:
- HostedZoneId
- HostedZoneName
- SubDomainNameWithDot
ParameterLabels:
GitHubRepo:
default: Git Repo
GitHubBranch:
default: Git Branch
PipelineApprovalAction:
default: Approval action
PipelineApprovalEmail:
default: Email address
AlertTopicArn:
default: SSM Parameter for the SNS Alert Topic Arn
HostedZoneId:
default: HostedZone Id
HostedZoneName:
default: HostedZone Name
SubDomainNameWithDot:
default: Sub domain name with trailing .
Parameters:
GitHubOAuthToken:
Description: OAuth token used by AWS CodePipeline to connect to GitHub
NoEcho: true
Type: String
Default: '{{resolve:secretsmanager:githubtoken:SecretString}}'
GitHubOwner:
Description: GitHub username owning the repo
Type: String
Default: BIBSYSDEV
GitHubRepo:
Type: String
Default: InterLibraryLoan-react-frontend
Description: Git repository name
GitHubBranch:
Type: String
Default: develop
Description: Git repository branch
PipelineApprovalAction:
Description: Do you want to add a manual approval action to the Release stage of this Pipeline?
AllowedValues:
- 'Yes'
- 'No'
Default: 'No'
Type: String
PipelineApprovalEmail:
Type: String
Default: ''
Description: The target email address for pipeline approval messages. Required when PipelineApprovalAction is Yes
AllowedPattern: '(^$|^[_A-Za-z0-9-\+\.]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$)'
ConstraintDescription: Valid email address or empty
AlertTopicArn:
Type: 'AWS::SSM::Parameter::Value<String>'
Default: '/alert/topicArn'
SubDomainNameWithDot:
Description: "Name that is used to create the DNS entry, with trailing dot, e.g.\
\ \xA7{SubDomainNameWithDot}\xA7{HostedZoneName}. Leave blank for naked (or\
\ apex and bare) domain. Requires ParentZoneStack parameter!"
Type: String
Default: 'ill.'
HostedZoneId:
Description: 'The Route53 hosted zone ID'
Type: 'AWS::SSM::Parameter::Value<String>'
Default: '/hostedzone/id'
HostedZoneName:
Description: 'The Route53 hosted zone name'
Type: 'AWS::SSM::Parameter::Value<String>'
Default: '/hostedzone/name'
DomainCertificateArn:
Description: 'The domain certificate ARN'
Type: 'AWS::SSM::Parameter::Value<String>'
Default: '/ill/cloudFrontCertificateArn'
ExistingBucketName:
Description: '(Optional) The name of an existing S3 bucket, or empty to create a new bucket'
Type: String
Default: ''
MinLength: 0
MaxLength: 100
AllowedPattern: '(^$|^[A-Za-z0-9-]+$)'
ConstraintDescription: 'Valid bucket name'
Conditions:
IsPipelineApprovalActionCondition: !Equals [!Ref PipelineApprovalAction, 'Yes']
HasApprovalEmailAddress: !Not [!Equals [!Ref PipelineApprovalEmail, '']]
HasAlertTopic: !Not [!Equals [!Ref AlertTopicArn, '']]
IsCreateNewBucketCondition: !Equals [!Ref ExistingBucketName, '']
Resources:
ArtifactsBucket:
Type: 'AWS::S3::Bucket'
Metadata:
cfn_nag:
rules_to_suppress:
- id: W35
reason: 'Skip access logging for artifacts bucket'
- id: W41
reason: 'Skip encryption for artifacts bucket'
- id: W51
reason: 'Skip bucket policy for artifacts bucket'
DependsOn: CloudFormationRole # make sure that CloudFormationRole is deleted last
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
AccessControl: Private
VersioningConfiguration:
Status: Enabled
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
LifecycleConfiguration:
Rules:
- Id: DeleteContentAfter8Days
Status: Enabled
ExpirationInDays: 8
PipelineApprovalTopic:
Type: AWS::SNS::Topic
Metadata:
cfn_nag:
rules_to_suppress:
- id: W47
reason: KMS key not relevant
Condition: IsPipelineApprovalActionCondition
Properties:
Subscription: # When adding Subscription, SNS formats the messages before sending
- !If [HasApprovalEmailAddress, { Endpoint: !Ref PipelineApprovalEmail, Protocol: email }, !Ref 'AWS::NoValue']
PipelineRole:
Type: 'AWS::IAM::Role'
Metadata:
cfn_nag:
rules_to_suppress:
- id: W11
reason: Pipeline needs these permissions
- id: W76
reason: Pipeline needs these permissions
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- 'codepipeline.amazonaws.com'
Action:
- 'sts:AssumeRole'
Policies:
- PolicyName: CodePipelineAccess
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- iam:PassRole
Resource: !GetAtt CloudFormationRole.Arn
Condition:
StringEqualsIfExists:
iam:PassedToService:
- cloudformation.amazonaws.com
- Effect: Allow
Action:
- s3:ListBucket
- s3:GetBucketVersioning
Resource:
- !Sub ${ArtifactsBucket.Arn}
- !If [
IsCreateNewBucketCondition,
!GetAtt WebsiteBucket.Arn,
!Sub 'arn:aws:s3:::${ExistingBucketName}',
]
- Effect: Allow
Action:
- s3:PutObject
- s3:PutObjectAcl
- s3:CreateMultipartUpload
- s3:ListMultipartUploadParts
- s3:AbortMultipartUpload
- s3:DeleteObject
- s3:GetObject
- s3:GetObjectVersion
Resource:
- !Sub '${ArtifactsBucket.Arn}/*'
- !If [
IsCreateNewBucketCondition,
!Sub '${WebsiteBucket.Arn}/*',
!Sub 'arn:aws:s3:::${ExistingBucketName}/*',
]
- Effect: Allow
Action:
- cloudformation:DescribeStacks
- cloudformation:CreateStack
- cloudformation:UpdateStack
- cloudformation:DescribeChangeSet
- cloudformation:CreateChangeSet
- cloudformation:ExecuteChangeSet
- cloudformation:DeleteChangeSet
Resource:
- !Sub 'arn:aws:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/${AWS::StackName}/*'
- Effect: Allow
Action:
- codebuild:BatchGetBuilds
- codebuild:StartBuild
Resource:
- !GetAtt CodeBuildProject.Arn
- !If
- IsPipelineApprovalActionCondition
- Effect: 'Allow'
Action:
- 'sns:Publish'
Resource: !Ref PipelineApprovalTopic
- !Ref AWS::NoValue
- Action:
- 'lambda:InvokeFunction'
Effect: Allow
Resource:
- !GetAtt InvalidateCloudfrontDistribution.Arn
- Action:
- 'ssm:getParameters'
Effect: Allow
Resource: '*'
CloudFormationRole:
Type: 'AWS::IAM::Role'
Metadata:
cfn_nag:
rules_to_suppress:
- id: W11
reason: CloudFormation needs permissions to create/update/delete resources in a stack (allow * resource in policy)
- id: F38
reason: CloudFormation needs permissions to create/update/delete resources in a stack (allow * resource with PassRole action on permissions policy)
- id: F3
reason: CloudFormation needs permissions to create/update/delete resources in a stack (allow * action on permissions policy)
- id: W76
reason: CloudFormation needs permissions to create/update/delete resources in a stack
Properties:
Description: 'This role is used both for the CodePipeline CFN stack, and the application CFN stack'
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- 'cloudformation.amazonaws.com'
Action:
- 'sts:AssumeRole'
Policies:
- PolicyName: CloudFormationAccess
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- apigateway:*
- application-autoscaling:*
- autoscaling:*
- cloudformation:*
- cloudfront:*
- cloudwatch:*
- codebuild:*
- codepipeline:*
- ec2:*
- ecs:*
- elasticfilesystem:*
- elasticloadbalancing:*
- events:*
- iam:*
- lambda:*
- logs:*
- kms:*
- rds:*
- s3:*
- secretsmanager:*
- sns:*
- ssm:*
- resource-groups:*
- route53:* # GetHostedZone
Resource: '*'
CodeBuildRole:
DependsOn: CloudFormationRole # make sure that CloudFormationRole is deleted last
Metadata:
cfn_nag:
rules_to_suppress:
- id: W11
reason: "Allow Resource 'bucket/*' for s3 and Resource '*' for CloudWatch Logs."
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- 'codebuild.amazonaws.com'
Action:
- 'sts:AssumeRole'
Policies:
- PolicyName: ServiceRole
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: CloudWatchLogsPolicy
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: !Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/*'
- Sid: S3GetPutObjects
Effect: Allow
Action:
- s3:GetObject
- s3:GetObjectVersion
- s3:PutObject
- s3:CreateMultipartUpload
- s3:ListMultipartUploadParts
- s3:AbortMultipartUpload
Resource: !Sub
- 'arn:aws:s3:::${BucketName}/*'
- BucketName: !Ref ArtifactsBucket
CodeBuildProject:
DependsOn: CloudFormationRole # make sure that CloudFormationRole is deleted last
Type: 'AWS::CodeBuild::Project'
Metadata:
cfn_nag:
rules_to_suppress:
- id: W32
reason: 'Skip encryption for CodeBuild project'
Properties:
Name: !Sub '${AWS::StackName}-build'
ServiceRole: !GetAtt 'CodeBuildRole.Arn'
Artifacts:
Type: NO_ARTIFACTS
Environment:
Type: LINUX_CONTAINER
ComputeType: BUILD_GENERAL1_SMALL
Image: aws/codebuild/standard:5.0
EnvironmentVariables:
- Name: S3_BUCKET
Value: !Ref ArtifactsBucket
- Name: REACT_APP_API_URL
Value: 'https://{{resolve:ssm:/api/domainName:1}}'
Source:
Type: GITHUB
Location: https://github.com/BIBSYSDEV/InterLibraryLoan-react-frontend.git
TimeoutInMinutes: 30
Cache:
Type: S3
Location: !Sub '${ArtifactsBucket}/codebuildcache'
Pipeline:
Type: AWS::CodePipeline::Pipeline
Properties:
Name: !Sub '${AWS::StackName}-Pipeline'
RoleArn: !GetAtt PipelineRole.Arn
RestartExecutionOnUpdate: true
# DisableInboundStageTransitions:
# - Reason: Approve Step
# StageName: Release
ArtifactStore:
Type: S3
Location: !Ref ArtifactsBucket
Tags:
- Key: 'automation:approval-timeout'
Value: '1'
Stages:
- Name: Source
Actions:
- Name: Source
ActionTypeId:
Category: Source
Owner: ThirdParty
Version: '1'
Provider: GitHub
Configuration:
Owner: !Ref GitHubOwner
OAuthToken: !Ref GitHubOAuthToken
Repo: !Ref GitHubRepo
Branch: !Ref GitHubBranch
PollForSourceChanges: false
OutputArtifacts:
- Name: SourceArtifacts
Namespace: SourceVariables
RunOrder: 1
- Name: Build
Actions:
- Name: TestAndBuildApp
ActionTypeId:
Category: Build
Owner: AWS
Provider: CodeBuild
Version: '1'
Configuration:
ProjectName: !Ref CodeBuildProject
InputArtifacts:
- Name: SourceArtifacts
OutputArtifacts:
- Name: BuildArtifacts
RunOrder: 1
- Name: UpdatePipeline
Actions:
- Name: DeployPipeline
ActionTypeId:
Category: Deploy
Owner: AWS
Provider: CloudFormation
Version: '1'
Configuration:
ActionMode: REPLACE_ON_FAILURE
RoleArn: !GetAtt 'CloudFormationRole.Arn'
StackName: !Ref 'AWS::StackName'
Capabilities: CAPABILITY_IAM
TemplatePath: 'SourceArtifacts::pipeline.yml'
ParameterOverrides: !Sub |
{
"GitHubRepo": "${GitHubRepo}",
"GitHubBranch": "${GitHubBranch}",
"PipelineApprovalAction": "${PipelineApprovalAction}",
"PipelineApprovalEmail": "${PipelineApprovalEmail}",
"AlertTopicArn": "/alert/topicArn",
"HostedZoneId": "/hostedzone/id",
"HostedZoneName": "/hostedzone/name",
"SubDomainNameWithDot": "${SubDomainNameWithDot}",
"DomainCertificateArn": "/ill/cloudFrontCertificateArn",
"ExistingBucketName": "${ExistingBucketName}"
}
InputArtifacts:
- Name: SourceArtifacts
RunOrder: 1
- Name: Release
Actions:
- !If
- IsPipelineApprovalActionCondition
- Name: ApprovalForRelease
ActionTypeId:
Category: Approval
Owner: AWS
Version: '1'
Provider: Manual
Configuration:
NotificationArn: !Ref PipelineApprovalTopic
CustomData: !Sub 'A new release is ready for the ${AWS::StackName} stack in account ${AWS::AccountId}. Commit message: "#{SourceVariables.CommitMessage}". Do you want to deploy the changes?'
ExternalEntityLink: 'https://aws.unit.no'
RunOrder: 1
- !Ref AWS::NoValue
- Name: CopyApplicationtoS3
ActionTypeId:
Category: Deploy
Owner: AWS
Provider: S3
Version: '1'
InputArtifacts:
- Name: BuildArtifacts
Configuration:
BucketName: !If [IsCreateNewBucketCondition, !Ref WebsiteBucket, !Ref ExistingBucketName]
Extract: true
RunOrder: 2
- Name: InvalidateDistribution
ActionTypeId:
Category: Invoke
Owner: AWS
Provider: Lambda
Version: '1'
Configuration:
FunctionName: !Ref InvalidateCloudfrontDistribution
UserParameters: !Sub '{"distribution_id": "${CloudFrontDistribution}"}'
RunOrder: 3
PipelineFailedNotification:
Type: 'AWS::Events::Rule'
Condition: HasAlertTopic
Properties:
EventPattern:
source:
- 'aws.codepipeline'
detail-type:
- 'CodePipeline Pipeline Execution State Change'
resources:
- !Ref Pipeline
detail:
state:
- FAILED
State: ENABLED
Targets:
- Arn: !Ref AlertTopicArn
Id: rule
InvalidateCloudfrontDistribution:
Type: AWS::Lambda::Function
Metadata:
cfn_nag:
rules_to_suppress:
- id: W89
reason: 'The Lambda does not need to be run inside a VPC, as it does not need access to other resources within a VPC'
- id: W92
reason: 'The Lambda does not need to reserve concurrency as it as rarely used and not related to processing of time-critical user requests'
Properties:
Code:
ZipFile: |
import boto3
import sys
import json
import datetime
import botocore
def handler(event, context):
print(json.dumps(event, default=str))
client = boto3.client('cloudfront')
timestamp_string = datetime.datetime.utcnow().strftime("%Y%m%d%H%M%S.%f")
data = event['CodePipeline.job']['data']
param = json.loads(data['actionConfiguration']['configuration'].get('UserParameters','{}'))
distributionId = param['distribution_id']
codepipeline = boto3.client('codepipeline')
job = event['CodePipeline.job']['id'];
try:
response = client.create_invalidation(
DistributionId=distributionId,
InvalidationBatch={
'Paths': {
'Quantity': 1,
'Items': [
'/*',
]
},
'CallerReference': timestamp_string
}
)
print(json.dumps(response, default=str))
invalidation_id = response['Invalidation']['Id']
waiter = client.get_waiter('invalidation_completed')
# Waits up to 10 mins
waiter.wait(
DistributionId=distributionId,
Id=invalidation_id
)
codepipeline.put_job_success_result(jobId=job);
return "Invalidation complete"
except botocore.exceptions.ClientError as e:
print('ClientError')
print(e)
print(e.response['Error']['Code'])
except botocore.exceptions.WaiterError as e:
print('WaiterError')
print(e)
except:
print("Exception:",sys.exc_info()[0])
codepipeline.put_job_failure_result(
jobId=job,
failureDetails={
'type': 'JobFailed',
'message': 'Invalidation Failed'
});
return "Invalidation failed"
Role: !GetAtt InvalidateCloudfrontDistributionFunctionRole.Arn
Handler: index.handler
Description: Lambda to invalidate Cloudfront distribution
Runtime: python3.8
Timeout: 900
InvalidateCloudfrontDistributionFunctionRole:
Type: AWS::IAM::Role
Metadata:
cfn_nag:
rules_to_suppress:
- id: W11
reason: 'Resource * required for codepipeline:PutJob*'
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: InvalidateCloudformationDistributionPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: CreateGetInvalidation
Effect: Allow
Action:
- 'cloudfront:CreateInvalidation'
- 'cloudfront:GetInvalidation'
Resource: !Sub 'arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}'
- Sid: SetPipelineResult
Effect: Allow
Action:
- 'codepipeline:PutJobSuccessResult'
- 'codepipeline:PutJobFailureResult'
Resource: '*'
WebsiteBucket:
Type: 'AWS::S3::Bucket'
Condition: IsCreateNewBucketCondition
Metadata:
cfn_nag:
rules_to_suppress:
- id: W35
reason: 'Access logging handled by CloudFront'
- id: W41
reason: 'Skip encryption for website bucket'
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
AccessControl: Private
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
VersioningConfiguration:
Status: Enabled
MetricsConfigurations:
- Id: EntireBucket
Tags:
- Key: description
Value: !Sub 'Frontend for ${AWS::StackName}'
WebsiteBucketPolicy:
Type: AWS::S3::BucketPolicy
Condition: IsCreateNewBucketCondition
Properties:
Bucket: !If [IsCreateNewBucketCondition, !Ref WebsiteBucket, !Ref ExistingBucketName]
PolicyDocument:
Statement:
- Effect: 'Allow'
Action:
- 's3:GetObject'
Resource: !Sub
- 'arn:aws:s3:::${WebsiteBucketName}/*'
- WebsiteBucketName: !If [IsCreateNewBucketCondition, !Ref WebsiteBucket, !Ref ExistingBucketName]
Principal:
AWS: !Sub 'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${CloudFrontOriginAccessIdentity}'
CloudFrontOriginAccessIdentity:
Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
Properties:
CloudFrontOriginAccessIdentityConfig:
Comment: !Sub
- '${WebsiteBucketName}-access-identity'
- WebsiteBucketName: !If [IsCreateNewBucketCondition, !Ref WebsiteBucket, !Ref ExistingBucketName]
CloudFrontDistribution:
Type: AWS::CloudFront::Distribution
Metadata:
cfn_nag:
rules_to_suppress:
- id: W70
reason: 'Cloudfront _does_ use minimum protocol version TLS 1.2'
Properties:
DistributionConfig:
Comment: CDN for static website stored in S3
Aliases:
- !Sub '${SubDomainNameWithDot}${HostedZoneName}'
DefaultCacheBehavior:
AllowedMethods: ['GET', 'HEAD', 'OPTIONS']
CachedMethods: ['GET', 'HEAD', 'OPTIONS']
Compress: true
DefaultTTL: 0
ForwardedValues:
QueryString: false
Cookies:
Forward: none
TargetOriginId: !Sub
- 'S3-${WebsiteBucketName}'
- WebsiteBucketName: !If [IsCreateNewBucketCondition, !Ref WebsiteBucket, !Ref ExistingBucketName]
ViewerProtocolPolicy: redirect-to-https
DefaultRootObject: 'index.html'
PriceClass: PriceClass_100
Restrictions:
GeoRestriction:
RestrictionType: blacklist
Locations:
- RU
- CN
ViewerCertificate:
AcmCertificateArn: !Ref DomainCertificateArn
SslSupportMethod: sni-only
MinimumProtocolVersion: TLSv1.2_2019
CustomErrorResponses:
- ErrorCode: 404
ErrorCachingMinTTL: 10
ResponseCode: 200
ResponsePagePath: '/index.html'
- ErrorCode: 403
ErrorCachingMinTTL: 10
ResponseCode: 200
ResponsePagePath: '/index.html'
- ErrorCachingMinTTL: 0
ErrorCode: 400
- ErrorCachingMinTTL: 5
ErrorCode: 500
Logging:
Bucket: !GetAtt CloudFrontAccessLogsBucket.DomainName
Enabled: true
Origins:
- DomainName: !Sub
- '${WebsiteBucketName}.s3.${AWS::Region}.amazonaws.com'
- WebsiteBucketName: !If [IsCreateNewBucketCondition, !Ref WebsiteBucket, !Ref ExistingBucketName]
Id: !Sub
- 'S3-${WebsiteBucketName}'
- WebsiteBucketName: !If [IsCreateNewBucketCondition, !Ref WebsiteBucket, !Ref ExistingBucketName]
S3OriginConfig:
OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}'
# OriginPath: /timestamp # TODO
CloudFrontAccessLogsBucket:
Type: AWS::S3::Bucket
Metadata:
cfn_nag:
rules_to_suppress:
- id: W35
reason: 'Skip access log for this bucket'
- id: W41
reason: 'Skip encryption for access log bucket'
- id: W51
reason: 'Use default bucket policy'
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
AccessControl: Private
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
VersioningConfiguration:
Status: Enabled
Tags:
- Key: description
Value: !Sub 'CloudFront AccessLogs for ${AWS::StackName}'
CloudFrontTotalErrorRateAlarm:
Type: AWS::CloudWatch::Alarm
Metadata:
cfn_nag:
rules_to_suppress:
- id: W28
reason: 'Allow explicit name'
Properties:
AlarmName: !Sub 'CloudFront-Errors-${AWS::StackName}'
AlarmDescription: 'CDN error monitor'
MetricName: TotalErrorRate
Namespace: AWS/CloudFront
Dimensions:
- Name: DistributionId
Value: !Ref CloudFrontDistribution
Statistic: Sum
Period: 60
EvaluationPeriods: 1
ComparisonOperator: GreaterThanOrEqualToThreshold
Threshold: 5
AlarmActions:
- !Ref AlertTopicArn
CloudFrontTotalCacheHitRateAlarm:
Type: AWS::CloudWatch::Alarm
Metadata:
cfn_nag:
rules_to_suppress:
- id: W28
reason: 'Allow explicit name'
Properties:
AlarmName: !Sub 'CloudFront-Cache-Hit-Rate-${AWS::StackName}'
AlarmDescription: 'CDN cache monitor'
MetricName: CacheHitRate
Namespace: AWS/CloudFront
Dimensions:
- Name: DistributionId
Value: !Ref CloudFrontDistribution
Statistic: Average
Period: 300
EvaluationPeriods: 1
ComparisonOperator: LessThanOrEqualToThreshold
Threshold: .80
AlarmActions:
- !Ref AlertTopicArn
RecordSet:
Type: AWS::Route53::RecordSet
Properties:
ResourceRecords:
- !GetAtt CloudFrontDistribution.DomainName
HostedZoneId: !Ref HostedZoneId
Comment: CNAME for website
Name: !Sub '${SubDomainNameWithDot}${HostedZoneName}'
TTL: 900
Type: CNAME
Outputs:
WebsiteBucketName:
Description: The name of the website bucket
Value: !If [IsCreateNewBucketCondition, !Ref WebsiteBucket, !Ref ExistingBucketName]
CloudFrontDistribution:
Value: !Ref CloudFrontDistribution
CloudFrontDomainName:
Description: CloudFront domain name (For reference)
Value: !GetAtt CloudFrontDistribution.DomainName
AppCustomDomainName:
Description: App custom domain name
Value: !Ref RecordSet
AppEndpointURL:
Description: App endpoint URL
Value: !Sub 'https://${RecordSet}'
ArtifactsBucket:
Description: The artifacts bucket
Value: !Ref ArtifactsBucket