-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
Copy pathCloudFront.yaml
823 lines (742 loc) · 24.9 KB
/
CloudFront.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
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
AWSTemplateFormatVersion: "2010-09-09"
Description: 'CI/CD optimized AWS CloudFormation Sample Template for AWS CloudFront Distribution with Custom Origin with an example of using the AWS Application Load Balancer (ALB) and a basic Amazon EC2 Instance. AWS CloudFront Distribution is associated with Lambda@Edge for Security Headers inspection. In addition, AWS CloudFormation Template will provision an Examples of necessary IAM, S3, KMS and Security Groups resources. ### Before deployment please make sure that all parameters are reviewed and updated according the specific use case. ### **WARNING** This template creates one Amazon EC2 instance and an Application Load Balancer, KMS Keys, S3 bucket, CloudFront Distribution resources. You will be billed for the AWS resources used if you create a stack from this template.'
Metadata:
cfn-lint:
config:
regions:
- us-east-1
- us-west-2
Parameters:
Environment:
Description: Please specify the target environment.
Type: String
AllowedValues:
- prod
- staging
- dev
- qa
Default: dev
VpcId:
Description: Please specify the VPC ID.
Type: AWS::EC2::VPC::Id
ConstraintDescription: "Must be a valid VPC ID"
PublicSubnetId1:
Description: Please specify first public subnet ID.
Type: AWS::EC2::Subnet::Id
ConstraintDescription: "Must be a valid subnet ID in the selected VPC"
PublicSubnetId2:
Description: Please specify second public subnet ID.
Type: AWS::EC2::Subnet::Id
ConstraintDescription: "Must be a valid subnet ID in the selected VPC"
AppName:
Description: Application environment name.
Type: String
Default: example
AlternateDomainNames:
Description: CNAMEs (alternate domain names), if any, for the distribution. Example. mydomain.com
Type: String
Default: name.domain.com
ACMCertificateIdentifier:
Description: The AWS Certificate Manager (ACM) certificate identifier.
Type: String
Default: 1234567890abcdefgh
LambdaEventType:
Description: Please specify the event type that triggers a Lambda function invocation.
Type: String
AllowedValues:
- viewer-request
- origin-request
- origin-response
- viewer-response
Default: viewer-response
IPV6Enabled:
Description: Should CloudFront to respond to IPv6 DNS requests with an IPv6 address for your distribution.
Type: String
AllowedValues:
- "true"
- "false"
Default: "true"
EC2ImageId:
Description: EC2 AMI Id
Type: AWS::EC2::Image::Id
Default: ami-0d85a662720db9789
EC2InstanceType:
Description: Amazon EC2 instance type.
Type: String
AllowedValues:
- t2.small
- t2.medium
- t2.large
- t2.xlarge
- t2.2xlarge
- m4.large
- m4.xlarge
- m4.2xlarge
- m4.4xlarge
- m4.10xlarge
- m4.16xlarge
- m5.large
- m5.xlarge
- m5.2xlarge
- m5.4xlarge
- m5.12xlarge
- m5.24xlarge
- m5d.large
- m5d.xlarge
- m5d.2xlarge
- m5d.4xlarge
- m5d.12xlarge
- m5d.24xlarge
Default: t2.small
KeyPairName:
Description: EC2 KeyPair.
Type: AWS::EC2::KeyPair::KeyName
ConstraintDescription: "Must be the name of an existing EC2 KeyPair"
BootVolSize:
Description: EC2 Instance Boot volume size.
Type: String
Default: "100"
BootVolType:
Description: EC2 Instance Boot volume type.
Type: String
AllowedValues:
- gp2
- io1
- sc1
- st1
Default: gp2
ALBType:
Description: AWS Load Balancer Type.
Type: String
AllowedValues:
- application
- network
Default: application
OriginALBTGPort:
Description: Port number the application is running on, for Origin ALB Target Group and Health Check port.
Type: String
Default: "8080"
OriginProtocolPolicy:
Description: CloudFront Origin Protocol Policy to apply to your origin.
Type: String
AllowedValues:
- http-only
- match-viewer
- https-only
Default: http-only
Compress:
Description: 'CloudFront should support gzip compression requests: Accept-Encoding: gzip.'
Type: String
AllowedValues:
- "true"
- "false"
Default: "false"
DefaultTTL:
Description: The default time in seconds that objects stay in CloudFront caches before CloudFront forwards another request to your custom origin. By default, AWS CloudFormation specifies 86400 seconds (one day).
Type: String
Default: "0"
MaxTTL:
Description: The maximum time in seconds that objects stay in CloudFront caches before CloudFront forwards another request to your custom origin. By default, AWS CloudFormation specifies 31536000 seconds (one year).
Type: String
Default: "0"
MinTTL:
Description: The minimum amount of time that you want objects to stay in the cache before CloudFront queries your origin to see whether the object has been updated.
Type: String
Default: "0"
QueryString:
Description: CIndicates whether you want CloudFront to forward query strings to the origin that is associated with this cache behavior.
Type: String
AllowedValues:
- "true"
- "false"
Default: "true"
ForwardCookies:
Description: Forwards specified cookies to the origin of the cache behavior.
Type: String
AllowedValues:
- all
- whitelist
- none
Default: all
ViewerProtocolPolicy:
Description: The protocol that users can use to access the files in the origin that you specified in the TargetOriginId property when the default cache behavior is applied to a request.
Type: String
AllowedValues:
- redirect-to-https
- allow-all
- https-only
Default: redirect-to-https
PriceClass:
Description: The price class that corresponds with the maximum price that you want to pay for CloudFront service. If you specify PriceClass_All, CloudFront responds to requests for your objects from all CloudFront edge locations.
Type: String
AllowedValues:
- PriceClass_All
- PriceClass_100
- PriceClass_200
Default: PriceClass_All
SslSupportMethod:
Description: Specifies how CloudFront serves HTTPS requests.
Type: String
AllowedValues:
- sni-only
- vip
Default: sni-only
MinimumProtocolVersion:
Description: The minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections.
Type: String
AllowedValues:
- TLSv1
- TLSv1.2_2018
- TLSv1.1_2016
- TLSv1_2016
- SSLv3
Default: TLSv1
OriginKeepaliveTimeout:
Description: You can create a custom keep-alive timeout. All timeout units are in seconds. The default keep-alive timeout is 5 seconds, but you can configure custom timeout lengths. The minimum timeout length is 1 second; the maximum is 60 seconds.
Type: String
Default: "60"
OriginReadTimeout:
Description: You can create a custom origin read timeout. All timeout units are in seconds. The default origin read timeout is 30 seconds, but you can configure custom timeout lengths. The minimum timeout length is 4 seconds; the maximum is 60 seconds.
Type: String
Default: "30"
ALBScheme:
Description: Origin ALB scheme.
Type: String
AllowedValues:
- internet-facing
- internal
Default: internet-facing
ALBTargetGroupHealthCheckIntervalSeconds:
Description: Origin ALB Target Group Health Check Interval in Seconds.
Type: String
Default: "30"
ALBTargetGroupHealthCheckTimeoutSeconds:
Description: Origin ALB Target Group Health Check Timeout in Seconds.
Type: String
Default: "5"
ALBTargetGroupHealthyThresholdCount:
Description: Origin ALB Target Group Healthy Threshold Count.
Type: String
Default: "5"
ALBTargetGroupUnhealthyThresholdCount:
Description: Origin ALB Target Group Unhealthy Threshold Count.
Type: String
Default: "2"
ALBAttributeIdleTimeOut:
Description: Origin ALB Target Group Unhealthy Threshold Count.
Type: String
Default: "60"
ALBAttributeDeletionProtection:
Description: Origin ALB Target Group Unhealthy Threshold Count.
Type: String
AllowedValues:
- "true"
- "false"
Default: "false"
ALBAttributeRoutingHttp2:
Description: Origin ALB Target Group Unhealthy Threshold Count.
Type: String
AllowedValues:
- "true"
- "false"
Default: "true"
ALBTargetGroupAttributeDeregistration:
Description: Origin ALB Target Group Deregistration Timeout.
Type: String
Default: "300"
HealthCheckProtocol:
Description: Origin ALB Target Group Health Check Protocol.
Type: String
AllowedValues:
- HTTPS
- HTTP
Default: HTTP
HealthCheckPath:
Description: Origin ALB Target Group Health Check Path.
Type: String
Default: /health.html
LoggingBucketVersioning:
Description: The versioning state of an Amazon S3 bucket. If you enable versioning, you must suspend versioning to disable it.
Type: String
AllowedValues:
- Enabled
- Suspended
Default: Suspended
Resources:
# IAM ROLE USED FOR LOGGING KMS KEY ACCESS
AdministratorAccessIAMRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub AdministratorAccess-${AppName}
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/AdministratorAccess
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action:
- sts:AssumeRole
Path: /
# IAM ROLE USED FOR LAMBDA EDGE
LambdaEdgeIAMRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub ${AppName}-iam-lambda-edge-role-${Environment}
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: AllowLambdaServiceToAssumeRole
Effect: Allow
Principal:
Service:
- edgelambda.amazonaws.com
- lambda.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
- arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess
Path: /
Policies:
- PolicyName: PublishNewLambdaEdgeVersion
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- lambda:PublishVersion
Resource: '*'
# KMS KEY USED FOR LOGGING S3 BUCKET
LoggingBucketKMSKey:
Type: AWS::KMS::Key
DependsOn: AdministratorAccessIAMRole
Properties:
Description: Logging S3 Bucket KMS Key
Enabled: true
EnableKeyRotation: true
KeyPolicy:
Version: "2012-10-17"
Statement:
- Sid: Enable IAM policies to allow access to the Key
Effect: Allow
Principal:
AWS: !Sub arn:${AWS::Partition}:iam::${AWS::AccountId}:root
Action:
- kms:*
Resource: '*'
- Sid: Allow administration of the key
Effect: Allow
Principal:
AWS:
- !Sub arn:${AWS::Partition}:iam::${AWS::AccountId}:role/AdministratorAccess-${AppName}
Action:
- kms:Put*
- kms:ScheduleKeyDeletion
- kms:CancelKeyDeletion
- kms:Describe*
- kms:Revoke*
- kms:Disable*
- kms:Enable*
- kms:Delete*
- kms:List*
- kms:Update*
- kms:Create*
Resource: '*'
# KMS KEY ALIAS USED FOR LOGGING BUCKET
LoggingBucketKMSKeyAlias:
Type: AWS::KMS::Alias
Properties:
AliasName: !Sub alias/${AppName}/${Environment}/s3-logging-kms
TargetKeyId: !Sub ${LoggingBucketKMSKey}
# LOGGING S3 BUCKET
LoggingBucket:
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Type: AWS::S3::Bucket
DependsOn: LoggingBucketKMSKey
Metadata:
guard:
SuppressedRules:
- S3_BUCKET_DEFAULT_LOCK_ENABLED
- S3_BUCKET_VERSIONING_ENABLED
- S3_BUCKET_REPLICATION_ENABLED
- S3_BUCKET_LOGGING_ENABLED
Properties:
BucketName: !Sub ${AppName}-logging-${Environment}-${AWS::AccountId}-${AWS::Region}
OwnershipControls:
Rules:
- ObjectOwnership: ObjectWriter
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
AccessControl: LogDeliveryWrite
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
KMSMasterKeyID: !GetAtt LoggingBucketKMSKey.Arn
SSEAlgorithm: aws:kms
VersioningConfiguration:
Status: !Ref LoggingBucketVersioning
# LOGGING S3 BUCKET POLICY
LoggingBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref LoggingBucket
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: LoggingBucketPermissions
Effect: Allow
Principal:
AWS: !Sub arn:${AWS::Partition}:iam::${AWS::AccountId}:root
Action: s3:PutObject
Resource:
- !Sub arn:${AWS::Partition}:s3:::${LoggingBucket}/AWSLogs/${AWS::AccountId}/*
- Action: s3:*
Condition:
Bool:
aws:SecureTransport: false
Effect: Deny
Principal:
AWS: '*'
Resource:
- !Sub arn:${AWS::Partition}:s3:::${LoggingBucket}/AWSLogs/${AWS::AccountId}/*
# EC2 INSTANCE
EC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref EC2ImageId
InstanceType: !Ref EC2InstanceType
SubnetId: !Ref PublicSubnetId1
BlockDeviceMappings:
- DeviceName: /dev/sda1
Ebs:
VolumeSize: !Ref BootVolSize
VolumeType: !Ref BootVolType
SecurityGroupIds:
- !Ref EC2InstanceSG
- !Ref ALBExternalAccessSG
KeyName: !Ref KeyPairName
Tags:
- Key: Name
Value: !Sub ${AppName}-${Environment}-ec2-instance
- Key: Environment
Value: !Ref Environment
# EC2 INSTANCE SECURITY GROUP
EC2InstanceSG:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: EC2 Instance Security Group
VpcId: !Ref VpcId
Tags:
- Key: Name
Value: !Sub ${AppName}-${Environment}-ec2-instance-SG
- Key: Environment
Value: !Ref Environment
# SECURITY GROUP INGRESS
Tcp8080In:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: !Ref EC2InstanceSG
ToPort: "8080"
IpProtocol: tcp
FromPort: "8080"
SourceSecurityGroupId: !Ref ALBExternalAccessSG
# ORIGIN ALB
OriginALB:
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
Properties:
Name: !Sub ${AppName}-${Environment}-alb
Scheme: !Ref ALBScheme
Type: !Ref ALBType
LoadBalancerAttributes:
- Key: idle_timeout.timeout_seconds
Value: !Ref ALBAttributeIdleTimeOut
- Key: deletion_protection.enabled
Value: !Ref ALBAttributeDeletionProtection
- Key: routing.http2.enabled
Value: !Ref ALBAttributeRoutingHttp2
Subnets:
- !Ref PublicSubnetId1
- !Ref PublicSubnetId2
SecurityGroups:
- !Ref ALBExternalAccessSG
Tags:
- Key: Name
Value: !Sub ${AppName}-${Environment}-alb
- Key: Environment
Value: !Ref Environment
# ORIGIN ALB TARGET GROUP
OriginALBTG:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
DependsOn: OriginALB
Properties:
Name: !Sub ${AppName}-${Environment}-alb-tg
HealthCheckProtocol: !Ref HealthCheckProtocol
HealthCheckPath: !Ref HealthCheckPath
HealthCheckPort: !Sub ${OriginALBTGPort}
HealthCheckIntervalSeconds: !Ref ALBTargetGroupHealthCheckIntervalSeconds
HealthCheckTimeoutSeconds: !Ref ALBTargetGroupHealthCheckTimeoutSeconds
HealthyThresholdCount: !Ref ALBTargetGroupHealthyThresholdCount
UnhealthyThresholdCount: !Ref ALBTargetGroupUnhealthyThresholdCount
TargetGroupAttributes:
- Key: deregistration_delay.timeout_seconds
Value: !Ref ALBTargetGroupAttributeDeregistration
TargetType: instance
Targets:
- Id: !Ref EC2Instance
Port: !Ref OriginALBTGPort
Port: !Ref OriginALBTGPort
Protocol: HTTP
VpcId: !Ref VpcId
Tags:
- Key: Name
Value: !Sub ${AppName}-${Environment}-alb-tg
- Key: Environment
Value: !Ref Environment
# ORIGIN ALB HTTPS LISTENER
OriginALBHttpsListener:
Type: AWS::ElasticLoadBalancingV2::Listener
DependsOn: OriginALBTG
Properties:
DefaultActions:
- TargetGroupArn: !Ref OriginALBTG
Type: forward
LoadBalancerArn: !Ref OriginALB
Port: 443
Protocol: HTTPS
Certificates:
- CertificateArn: !Sub arn:${AWS::Partition}:acm:${AWS::Region}:${AWS::AccountId}:certificate/${ACMCertificateIdentifier}
SslPolicy: ELBSecurityPolicy-FS-2018-06
# ORIGIN ALB HTTPS LISTENER RULE
OriginALBHttpsListenerRule:
Type: AWS::ElasticLoadBalancingV2::ListenerRule
DependsOn: OriginALBHttpsListener
Properties:
Actions:
- Type: forward
TargetGroupArn: !Ref OriginALBTG
Conditions:
- Field: path-pattern
Values:
- /*
ListenerArn: !Ref OriginALBHttpsListener
Priority: 1
# ALB EXTERNAL ACCESS SECURITY GROUP
ALBExternalAccessSG:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Allow external access to ALB
VpcId: !Ref VpcId
Tags:
- Key: Name
Value: !Sub ${AppName}-${Environment}-alb-external-access-ingrees-SG
- Key: Environment
Value: !Ref Environment
# SECURITY GROUP INGRESS
HTTPSTcpIn:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: !Ref ALBExternalAccessSG
ToPort: 443
IpProtocol: tcp
FromPort: 443
CidrIp: 0.0.0.0/0
HTTPTcpIn:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: !Ref ALBExternalAccessSG
ToPort: 80
IpProtocol: tcp
FromPort: 80
CidrIp: 0.0.0.0/0
# SECURITY GROUP EGRESS
Tcp8080Out:
Type: AWS::EC2::SecurityGroupEgress
Properties:
GroupId: !Ref ALBExternalAccessSG
ToPort: 8080
IpProtocol: tcp
FromPort: 8080
DestinationSecurityGroupId: !Ref EC2InstanceSG
# CLOUDFRONT DISTRIBUTION
CloudFrontDistribution:
Type: AWS::CloudFront::Distribution
DependsOn:
- LoggingBucket
- LambdaEdgeFunction
Properties:
DistributionConfig:
Comment: Cloudfront Distribution pointing ALB Origin
Origins:
- DomainName: !GetAtt OriginALB.DNSName
Id: !Ref OriginALB
CustomOriginConfig:
HTTPPort: 80
HTTPSPort: 443
OriginProtocolPolicy: !Ref OriginProtocolPolicy
OriginKeepaliveTimeout: !Ref OriginKeepaliveTimeout
OriginReadTimeout: !Ref OriginReadTimeout
OriginSSLProtocols:
- TLSv1
- TLSv1.1
- TLSv1.2
- SSLv3
Enabled: true
HttpVersion: http2
Aliases:
- !Ref AlternateDomainNames
DefaultCacheBehavior:
AllowedMethods:
- GET
- HEAD
- DELETE
- OPTIONS
- PATCH
- POST
- PUT
Compress: !Ref Compress
DefaultTTL: !Ref DefaultTTL
MaxTTL: !Ref MaxTTL
MinTTL: !Ref MinTTL
SmoothStreaming: "false"
TargetOriginId: !Ref OriginALB
ForwardedValues:
QueryString: !Ref QueryString
Cookies:
Forward: !Ref ForwardCookies
ViewerProtocolPolicy: !Ref ViewerProtocolPolicy
LambdaFunctionAssociations:
- EventType: !Ref LambdaEventType
LambdaFunctionARN: !Ref LambdaEdgeVersion
PriceClass: !Ref PriceClass
ViewerCertificate:
AcmCertificateArn: !Sub arn:${AWS::Partition}:acm:${AWS::Region}:${AWS::AccountId}:certificate/${ACMCertificateIdentifier}
SslSupportMethod: !Ref SslSupportMethod
MinimumProtocolVersion: !Ref MinimumProtocolVersion
IPV6Enabled: !Ref IPV6Enabled
Logging:
Bucket: !Sub ${LoggingBucket}.s3.amazonaws.com
# LAMBDA@EDGE FUNCTION
LambdaEdgeFunction:
Type: AWS::Lambda::Function
Metadata:
guard:
SuppressedRules:
- LAMBDA_INSIDE_VPC
Properties:
Description: A custom Lambda@Edge function for serving custom headers from CloudFront Distribution
FunctionName: !Sub ${AppName}-lambda-edge-${Environment}
Handler: index.handler
Role: !GetAtt LambdaEdgeIAMRole.Arn
MemorySize: 128
Timeout: 5
Code:
ZipFile: |
'use strict';
exports.handler = (event, context, callback) => {
console.log('Adding additional headers to CloudFront response.');
const response = event.Records[0].cf.response;
response.headers['strict-transport-security'] = [{
key: 'Strict-Transport-Security',
value: 'max-age=86400; includeSubdomains; preload',
}];
response.headers['x-content-type-options'] = [{
key: 'X-Content-Type-Options',
value: 'nosniff',
}];
response.headers['x-frame-options'] = [{
key: 'X-Frame-Options',
value: "DENY"
}];
response.headers['content-security-policy'] = [{
key: 'Content-Security-Policy',
value: "default-src 'none'; img-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'"
}];
response.headers['x-xss-protection'] = [{
key: 'X-XSS-Protection',
value: "1; mode=block"
}];
response.headers['referrer-policy'] = [{
key: 'Referrer-Policy',
value: "same-origin"
}];
callback(null, response);
};
Runtime: nodejs20.x
LambdaEdgeVersion:
Type: AWS::Lambda::Version
Properties:
FunctionName: !Ref LambdaEdgeFunction
Outputs:
AdministratorAccessIAMRole:
Description: Administrator Access IAM Role
Value: !Ref AdministratorAccessIAMRole
Export:
Name: !Sub ${AppName}-iam-${Environment}-administrator-access-role
LoggingBucket:
Description: Name of S3 Logging bucket
Value: !Ref LoggingBucket
Export:
Name: !Sub ${AppName}-logging-${Environment}-${AWS::AccountId}-${AWS::Region}
LoggingBucketKMSKey:
Description: Logging Bucket KMS Key
Value: !Ref LoggingBucketKMSKey
Export:
Name: !Sub ${AppName}-${Environment}-s3-logging-kms
OriginALB:
Description: The URL of the Origin ALB
Value: !GetAtt OriginALB.DNSName
Export:
Name: !Sub ${AppName}-${Environment}-origin-alb-dns
ALBExternalAccessSGID:
Description: ALB External Access Security Group ID
Value: !Ref ALBExternalAccessSG
Export:
Name: !Sub ${AppName}-${Environment}-alb-external-access-ingrees-sg
EC2InstanceSGID:
Description: EC2 Instance Security Group ID
Value: !Ref EC2InstanceSG
Export:
Name: !Sub ${AppName}-${Environment}-ec2-instance-sg
EC2InstanceDNS:
Description: EC2 Instance DNS Name
Value: !GetAtt EC2Instance.PrivateDnsName
Export:
Name: !Sub ${AppName}-${Environment}-ec2-instance-dns
EC2InstanceIP:
Description: EC2 Instance IP Address
Value: !GetAtt EC2Instance.PrivateIp
Export:
Name: !Sub ${AppName}-${Environment}-ec2-instance-ip-address
EC2InstanceID:
Description: EC2 Instance Instance ID
Value: !Ref EC2Instance
Export:
Name: !Sub ${AppName}-${Environment}-ec2-instance-id
CloudFrontEndpoint:
Description: Endpoint for Cloudfront Distribution
Value: !Ref CloudFrontDistribution
Export:
Name: !Sub ${AppName}-${Environment}-cloudfront-distribution
AlternateDomainNames:
Description: Alternate Domain Names (CNAME)
Value: !Ref AlternateDomainNames
LambdaEdgeFunction:
Description: The Name of the Lambda@Edge Function
Value: LambdaEdgeFunction
Export:
Name: !Sub ${AppName}-${Environment}-lambda-edge-function-3
LambdaEdgeFunctionARN:
Description: The ARN of the Lambda@Edge Function
Value: !GetAtt LambdaEdgeFunction.Arn
Export:
Name: !Sub ${AppName}-${Environment}-lambda-edge-function-arn-3
LambdaEdgeVersion:
Description: Lambda@Edge Version Function
Value: !GetAtt LambdaEdgeVersion.Version