-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstaticwebsite.yaml
1170 lines (1103 loc) · 37.3 KB
/
staticwebsite.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
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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
AWSTemplateFormatVersion: "2010-09-09"
Description: |
Static web site stack with CodePipeline and CodeBuild deployment from
CodeCommit repository. Includes redirect from www to base domain, access
logs written to S3, SSL via Amazon Certificate Manager, CloudFront CDN, and
Route 53 DNS entries. S3 access logs analysis and visualization using Elasticsearch and Kibana.
Parameters:
# Domain: example-com
ProjectName:
Type: String
Description: "The project name"
MinLength: 4
MaxLength: 253
AllowedPattern: "[a-z0-9]+[-.a-z0-9]*"
ConstraintDescription: |
Provide a valid project name using only lowercase letters,
numbers, and dash (-).
# Domain: example.com
DomainName:
Type: String
Description: "The base domain name for the web site (no 'www')"
MinLength: 4
MaxLength: 253
AllowedPattern: "[a-z0-9]+[-.a-z0-9]*(\\.[a-z][a-z]+)+"
ConstraintDescription: |
Provide a valid domain name using only lowercase letters,
numbers, ., and dash (-)
DefaultTTL:
Type: Number
Description: "CloudFront default cache lifetime in seconds"
Default: 30
MinimumTTL:
Description: "CloudFront minimum cache lifetime in seconds"
Default: 5
Type: Number
PriceClass:
Description: "CloudFront price class. Default is US-only, PriceClass_All is worldwide but more expensive."
Default: PriceClass_100
AllowedValues:
- PriceClass_100
- PriceClass_200
- PriceClass_All
Type: String
LogExpirationInDays:
Description: "How long to hold site access logs in S3."
Default: 30
Type: Number
PreExistingLogsBucket:
Description: |
Optional pre-existing access logs bucket.
Leave empty to have access logs bucket created and managed by this stack.
Type: String
Default: ""
PreExistingSiteBucket:
Description: |
Optional pre-existing website bucket.
Leave empty to have website bucket created and managed by this stack.
Type: String
Default: ""
PreExistingRedirectBucket:
Description: |
Optional pre-existing redirect bucket.
Leave empty to have redirect bucket created and managed by this stack.
Type: String
Default: ""
PreExistingCodeCommitRepository:
Description: |
Optional pre-existing CodeCommit repository.
Leave empty to have repository created and managed by this stack.
Type: String
Default: ""
PreExistingCodePipelineBucket:
Description: |
Optional name of pre-existing CodePipeline artifact bucket.
Leave empty to have CodePipeline bucket created and managed by this stack.
Type: String
Default: ""
PreExistingHostedZoneDomain:
Description: |
Optional pre-existing Route 53 hosted zone.
Leave empty to have hosted zone created and managed by this stack.
Type: String
Default: ""
PreExistingHostedZoneId:
Description: |
Optional pre-existing Route 53 hosted zone id.
Fill it if you already have a hosted zone.
Leave empty to have hosted zone id created and managed by this stack.
Type: String
Default: ""
ESIndexExpirationinDays:
Description: How long to hold indexes in Elasticsearch.
Type: Number
Default: 0
PreExistingCertificate:
Description: |
Optional pre-existing Certificate.
Leave empty to have certificate created and managed by this stack.
Type: String
Default: ""
Conditions:
NeedsNewLogsBucket: !Equals [!Ref PreExistingLogsBucket, ""]
NeedsNewRedirectBucket: !Equals [!Ref PreExistingRedirectBucket, ""]
NeedsNewSiteBucket: !Equals [!Ref PreExistingSiteBucket, ""]
NeedsNewCodePipelineBucket: !Equals [!Ref PreExistingCodePipelineBucket, ""]
NeedsNewCodeCommitRepository:
!Equals [!Ref PreExistingCodeCommitRepository, ""]
NeedsNewHostedZone: !Equals [!Ref PreExistingHostedZoneDomain, ""]
NeedsNewCertificate: !Equals [!Ref PreExistingCertificate, ""]
Mappings:
RegionMap:
ap-northeast-1:
S3hostedzoneID: "Z2M4EHUR26P7ZW"
websiteendpoint: "s3-website-ap-northeast-1.amazonaws.com"
ap-northeast-2:
S3hostedzoneID: "Z3W03O7B5YMIYP"
websiteendpoint: "s3-website.ap-northeast-2.amazonaws.com"
ap-south-1:
S3hostedzoneID: "Z11RGJOFQNVJUP"
websiteendpoint: "s3-website.ap-south-1.amazonaws.com"
ap-southeast-1:
S3hostedzoneID: "Z3O0J2DXBE1FTB"
websiteendpoint: "s3-website-ap-southeast-1.amazonaws.com"
ap-southeast-2:
S3hostedzoneID: "Z1WCIGYICN2BYD"
websiteendpoint: "s3-website-ap-southeast-2.amazonaws.com"
eu-central-1:
S3hostedzoneID: "Z21DNDUVLTQW6Q"
websiteendpoint: "s3-website.eu-central-1.amazonaws.com"
eu-west-1:
S3hostedzoneID: "Z1BKCTXD74EZPE"
websiteendpoint: "s3-website-eu-west-1.amazonaws.com"
sa-east-1:
S3hostedzoneID: "Z7KQH4QJS55SO"
websiteendpoint: "s3-website-sa-east-1.amazonaws.com"
us-east-1:
S3hostedzoneID: "Z3AQBSTGFYJSTF"
websiteendpoint: "s3-website-us-east-1.amazonaws.com"
us-east-2:
S3hostedzoneID: "Z2O1EMRO9K5GLX"
websiteendpoint: "s3-website.us-east-2.amazonaws.com"
us-west-1:
S3hostedzoneID: "Z2F56UZL2M1ACD"
websiteendpoint: "s3-website-us-west-1.amazonaws.com"
us-west-2:
S3hostedzoneID: "Z3BJ6K6RIION7M"
Resources:
# Bucket for CloudFront and S3 access logs: logs-example-com
LogsBucket:
Condition: NeedsNewLogsBucket
Type: "AWS::S3::Bucket"
Properties:
BucketName: !Sub "logs-${ProjectName}"
AccessControl: LogDeliveryWrite
LifecycleConfiguration:
Rules:
- Id: "LogExpirationRule"
Status: "Enabled"
ExpirationInDays: !Ref LogExpirationInDays
NotificationConfiguration:
LambdaConfigurations:
- Event: "s3:ObjectCreated:*"
Function: !GetAtt LogsToCloudwatchLambda.Arn
DeletionPolicy: Delete
DependsOn: PermissionForS3ToInvokeLogsToCloudwatchLambda
# Bucket to redirect to example.com: www.example.com
RedirectBucket:
Condition: NeedsNewRedirectBucket
Type: "AWS::S3::Bucket"
Properties:
BucketName: !Sub "www.${DomainName}"
AccessControl: BucketOwnerFullControl
# logs.example.com/logs/s3/www.example.com/
LoggingConfiguration:
DestinationBucketName:
!If [NeedsNewLogsBucket, !Ref LogsBucket, !Ref PreExistingLogsBucket]
LogFilePrefix: !Sub "logs/s3/www.${DomainName}/"
WebsiteConfiguration:
RedirectAllRequestsTo:
HostName: !Ref DomainName
Protocol: https
DeletionPolicy: Delete
# Bucket for site content: example.com
SiteBucket:
Condition: NeedsNewSiteBucket
Type: "AWS::S3::Bucket"
Properties:
BucketName: !Ref DomainName
AccessControl: PublicRead
WebsiteConfiguration:
IndexDocument: index.html
ErrorDocument: error.html
# logs.example.com/logs/s3/example.com/
LoggingConfiguration:
DestinationBucketName:
!If [NeedsNewLogsBucket, !Ref LogsBucket, !Ref PreExistingLogsBucket]
LogFilePrefix: !Sub "logs/s3/${DomainName}/"
DeletionPolicy: Delete
# Site bucket policy
SiteBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref SiteBucket
PolicyDocument:
Version: "2012-10-17"
Statement:
Effect: Allow
Principal: "*"
Action: s3:GetObject
Resource: !Sub arn:aws:s3:::${SiteBucket}/*
# Permission for s3 to invoke lambda which will fetch the logs from s3 and store in cloudwatch
PermissionForS3ToInvokeLogsToCloudwatchLambda:
Type: "AWS::Lambda::Permission"
Properties:
Action: "lambda:InvokeFunction"
FunctionName: !GetAtt LogsToCloudwatchLambda.Arn
Principal: "s3.amazonaws.com"
SourceArn: !Join ["", ["arn:aws:s3:::", !Sub "logs-${ProjectName}"]]
# Lambda to move logs from S3 logs bucket to cloudwatch
LogsToCloudwatchLambda:
Type: AWS::Lambda::Function
Properties:
Description: Lambda to move logs from S3 logs bucket to cloudwatch
Handler: readS3Logs.handler
Role: !GetAtt LogsToCloudwatchLambdaExecutionRole.Arn
Code:
S3Bucket: !Join
- ""
- - !ImportValue LambdaCodeBucket
S3Key: "lambdas/readS3Logs.zip"
Environment:
Variables:
S3_LOG_GROUP: !Ref SiteLogGroup
CF_LOG_GROUP: !Ref CloudfrontLogGroup
Timeout: 30
Runtime: nodejs6.10
# Role for Lambda to access objects within S3 Logs bucket
LogsToCloudwatchLambdaExecutionRole:
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: S3Policy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- "S3:GetObject"
- "s3:PutObject"
- "S3:DeleteObject"
Resource: !Sub "arn:aws:s3:::logs-${ProjectName}/*"
- Effect: "Allow"
Action:
- "logs:CreateLogGroup"
- "logs:CreateLogStream"
- "logs:PutLogEvents"
- "logs:GetLogEvents"
- "logs:DescribeLogStreams"
Resource: "arn:aws:logs:*:*:*"
# Log group for s3 access logs
SiteLogGroup:
Type: "AWS::Logs::LogGroup"
Properties:
LogGroupName: !Sub "${ProjectName}S3Logs"
# Log group for Cloudfront logs
CloudfrontLogGroup:
Type: "AWS::Logs::LogGroup"
Properties:
LogGroupName: !Sub "${ProjectName}CFLogs"
# Git repository
CodeCommitRepository:
Condition: NeedsNewCodeCommitRepository
Type: "AWS::CodeCommit::Repository"
Properties:
RepositoryDescription: !Sub "Git repository for ${DomainName}"
RepositoryName: !Ref ProjectName
DeletionPolicy: Delete
# Role for CodeBuild
CodeBuildServiceRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service:
- "codebuild.amazonaws.com"
Action:
- "sts:AssumeRole"
Path: "/"
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/AWSCodeCommitFullAccess"
- "arn:aws:iam::aws:policy/AmazonS3FullAccess"
- "arn:aws:iam::aws:policy/CloudWatchLogsFullAccess"
- "arn:aws:iam::aws:policy/AWSCodeBuildDeveloperAccess"
# CodeBuild Project
CodeBuildProject:
Type: AWS::CodeBuild::Project
Properties:
Name: !Ref ProjectName
ServiceRole: !GetAtt CodeBuildServiceRole.Arn
Artifacts:
Type: NO_ARTIFACTS
Environment:
Type: linuxContainer
ComputeType: BUILD_GENERAL1_SMALL
Image: aws/codebuild/nodejs:8.11.0
EnvironmentVariables:
- Name: SITE_BUCKET
Value: !Ref SiteBucket
Source:
Location: !Sub "https://git-codecommit.${AWS::Region}.amazonaws.com/v1/repos/${ProjectName}"
Type: CODECOMMIT
BuildSpec: |
version: 0.1
phases:
install:
commands:
- sudo npm install
build:
commands:
- sudo node_modules/.bin/hexo clean
- sudo node_modules/.bin/hexo algolia
- sudo node_modules/.bin/hexo generate
post_build:
commands:
- aws s3 sync public/ s3://$SITE_BUCKET/ --delete
TimeoutInMinutes: 10
# Role for CodePipeline
CodePipelineRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- "codepipeline.amazonaws.com"
Action:
- "sts:AssumeRole"
Path: "/"
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/AWSCodeCommitFullAccess"
- "arn:aws:iam::aws:policy/AmazonS3FullAccess"
- "arn:aws:iam::aws:policy/CloudWatchLogsFullAccess"
- "arn:aws:iam::aws:policy/AWSCodeBuildDeveloperAccess"
# Bucket for CodePipeline artifact storage: codepipeline.example.com
CodePipelineBucket:
Condition: NeedsNewCodePipelineBucket
Type: "AWS::S3::Bucket"
Properties:
BucketName: !Sub "codepipeline-${ProjectName}"
VersioningConfiguration:
Status: Enabled
DeletionPolicy: Delete
# CodePipeline for the static website
CodePipeline:
Type: "AWS::CodePipeline::Pipeline"
Properties:
Name: !Sub "${ProjectName}-codepipeline"
ArtifactStore:
Type: S3
Location:
!If [
NeedsNewCodePipelineBucket,
!Ref CodePipelineBucket,
!Ref PreExistingCodePipelineBucket,
]
RestartExecutionOnUpdate: false
RoleArn: !GetAtt CodePipelineRole.Arn
Stages:
- Name: Source
Actions:
- Name: SourceAction
ActionTypeId:
Category: Source
Owner: AWS
Provider: CodeCommit
Version: 1
Configuration:
RepositoryName:
!If [
NeedsNewCodeCommitRepository,
!Ref ProjectName,
!Ref PreExistingCodeCommitRepository,
]
BranchName: master
OutputArtifacts:
- Name: SiteSource
RunOrder: 1
- Name: Build
Actions:
- Name: InvokeAction
InputArtifacts:
- Name: SiteSource
ActionTypeId:
Category: Build
Owner: AWS
Provider: CodeBuild
Version: 1
Configuration:
ProjectName: !Ref ProjectName
OutputArtifacts:
- Name: SiteContent
RunOrder: 1
# Create and validate certificate role
CertificateLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Path: /
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
Policies:
- PolicyName: CFNCertificateDomainResourceRecordProvider
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- acm:RequestCertificate
- acm:DescribeCertificate
- acm:UpdateCertificateOptions
- acm:DeleteCertificate
Resource:
- "*"
- Effect: Allow
Action:
- route53:ChangeResourceRecordSets
Resource:
!Join [
"",
[
"arn:aws:route53:::hostedzone/",
!If [
NeedsNewHostedZone,
!Ref Route53HostedZone,
!Ref PreExistingHostedZoneId,
],
],
]
- Effect: Allow
Action:
- logs:*
Resource: arn:aws:logs:*:*:*
# Lambda to create and validate certificate
CreateAndValidateCertificateLambda:
Type: AWS::Lambda::Function
Properties:
Description: Lambda to create and validate certificate
Handler: certificateValidator.handler
Role: !GetAtt CertificateLambdaRole.Arn
Code:
S3Bucket: !Join
- ""
- - !ImportValue LambdaCodeBucket
S3Key: "lambdas/certificateValidator.zip"
Environment:
Variables:
EXEC_THRESHOLD_SECONDS: 200
Timeout: 300
Runtime: nodejs6.10
# Certificate for HTTPS accesss through CloudFront
Certificate:
Type: Custom::Certificate
Properties:
DomainName: !Ref DomainName
ValidationMethod: DNS
ServiceToken: !GetAtt CreateAndValidateCertificateLambda.Arn
# Check ACM Certificate validity status
IssuedCertificate:
Type: Custom::IssuedCertificate
Properties:
CertificateArn: !GetAtt Certificate.CertificateArn
LambdaArn: !GetAtt CreateAndValidateCertificateLambda.Arn
Region: !Ref "AWS::Region"
ServiceToken: !GetAtt CreateAndValidateCertificateLambda.Arn
DependsOn: DomainValidationRecord
# Generates DNS Record for certificate
CertificateDNSRecord:
Type: Custom::CertificateDNSRecord
Properties:
CertificateArn: !GetAtt Certificate.CertificateArn
ServiceToken: !GetAtt CreateAndValidateCertificateLambda.Arn
# Validates certificate by adding record in DNS.
DomainValidationRecord:
Type: AWS::Route53::RecordSetGroup
Properties:
HostedZoneId:
!If [
NeedsNewHostedZone,
!Ref Route53HostedZone,
!Ref PreExistingHostedZoneId,
]
RecordSets:
- Name: !GetAtt CertificateDNSRecord.Name
Type: "CNAME"
TTL: 300
ResourceRecords:
- !GetAtt CertificateDNSRecord.Value
# CDN serves S3 content over HTTPS for example.com
CloudFrontDistribution:
Type: "AWS::CloudFront::Distribution"
Properties:
DistributionConfig:
Enabled: true
Aliases:
- !Ref DomainName
DefaultRootObject: index.html
PriceClass: !Ref PriceClass
Origins:
- DomainName:
!Join [
"",
[
!Ref DomainName,
".",
!FindInMap [RegionMap, !Ref "AWS::Region", websiteendpoint],
],
]
Id: S3Origin
CustomOriginConfig:
HTTPPort: 80
HTTPSPort: 443
OriginProtocolPolicy: http-only
DefaultCacheBehavior:
TargetOriginId: S3Origin
AllowedMethods:
- GET
- HEAD
Compress: true
DefaultTTL: !Ref DefaultTTL
MinTTL: !Ref MinimumTTL
ForwardedValues:
QueryString: false
Cookies:
Forward: none
ViewerProtocolPolicy: redirect-to-https
# logs.example.com/logs/cloudfront/example.com/
Logging:
Bucket:
!Join [
"",
[
!If [
NeedsNewLogsBucket,
!Ref LogsBucket,
!Ref PreExistingLogsBucket,
],
".s3.amazonaws.com",
],
]
Prefix: !Sub "logs/cloudfront/${DomainName}/"
IncludeCookies: false
ViewerCertificate:
AcmCertificateArn: !GetAtt IssuedCertificate.CertificateArn
SslSupportMethod: sni-only
# CDN serves S3 content over HTTPS for www.example.com
RedirectCloudFrontDistribution:
Type: "AWS::CloudFront::Distribution"
Properties:
DistributionConfig:
Enabled: true
Aliases:
- !If [
NeedsNewRedirectBucket,
!Ref RedirectBucket,
!Ref PreExistingRedirectBucket,
]
PriceClass: PriceClass_100
Origins:
- DomainName:
!Join [
"",
[
!If [
NeedsNewRedirectBucket,
!Ref RedirectBucket,
!Ref PreExistingRedirectBucket,
],
".",
!FindInMap [RegionMap, !Ref "AWS::Region", websiteendpoint],
],
]
Id: RedirectS3Origin
CustomOriginConfig:
HTTPPort: 80
HTTPSPort: 443
OriginProtocolPolicy: http-only
DefaultCacheBehavior:
TargetOriginId: RedirectS3Origin
AllowedMethods:
- GET
- HEAD
DefaultTTL: !Ref DefaultTTL
MinTTL: !Ref MinimumTTL
ForwardedValues:
QueryString: false
Cookies:
Forward: none
ViewerProtocolPolicy: allow-all
# logs.example.com/logs/cloudfront/www.example.com/
Logging:
Bucket:
!Join [
"",
[
!If [
NeedsNewLogsBucket,
!Ref LogsBucket,
!Ref PreExistingLogsBucket,
],
".s3.amazonaws.com",
],
]
Prefix: !Sub "logs/cloudfront/www.${DomainName}/"
IncludeCookies: false
ViewerCertificate:
AcmCertificateArn: !GetAtt IssuedCertificate.CertificateArn
SslSupportMethod: sni-only
# DNS: example.com, www.example.com
Route53HostedZone:
Condition: NeedsNewHostedZone
Type: "AWS::Route53::HostedZone"
Properties:
HostedZoneConfig:
Comment: !Sub "Created by CloudFormation stack: ${AWS::StackName}"
Name: !Ref DomainName
DeletionPolicy: Delete
Route53RecordSetGroup:
Type: "AWS::Route53::RecordSetGroup"
Properties:
HostedZoneId:
!If [NeedsNewHostedZone, !Ref Route53HostedZone, !Ref "AWS::NoValue"]
HostedZoneName:
!If [
NeedsNewHostedZone,
!Ref "AWS::NoValue",
!Sub "${PreExistingHostedZoneDomain}.",
]
RecordSets:
# example.com
- Name: !Sub "${DomainName}."
Type: A
# Resolve to CloudFront distribution
AliasTarget:
HostedZoneId: Z2FDTNDATAQYW2 # CloudFront
DNSName: !GetAtt CloudFrontDistribution.DomainName
# www.example.com
- Name: !Sub "www.${DomainName}."
Type: A
# Resolve to Redirect CloudFront distribution
AliasTarget:
HostedZoneId: Z2FDTNDATAQYW2 # CloudFront
DNSName: !GetAtt RedirectCloudFrontDistribution.DomainName
# Elasticsearch for analysis and search to get insights from logs
SiteElasticsearch:
Type: "AWS::Elasticsearch::Domain"
Properties:
DomainName: !Sub "${ProjectName}"
AccessPolicies:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
AWS: !Join
- ":"
- - "arn:aws:iam:"
- !Ref "AWS::AccountId"
- "root"
Action:
- "es:ESHttpGet"
Resource: !Join
- ":"
- - "arn:aws:es"
- !Ref "AWS::Region"
- !Ref "AWS::AccountId"
- !Sub "domain/${ProjectName}/*"
EBSOptions:
EBSEnabled: true
VolumeSize: 10
VolumeType: "gp2"
ElasticsearchClusterConfig:
DedicatedMasterEnabled: false
InstanceCount: 1
InstanceType: "t2.small.elasticsearch"
ZoneAwarenessEnabled: false
ElasticsearchVersion: "6.3"
# Role for Lambda to transform logs and upload to elasticsearch
LogsToElasticsearchLambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal: { Service: [lambda.amazonaws.com] }
Action: ["sts:AssumeRole"]
Path: /
Policies:
- PolicyName: "ElasticSearchPolicy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- "es:*"
Resource: "arn:aws:es:*:*:*"
- Effect: "Allow"
Action:
- "logs:CreateLogGroup"
- "logs:CreateLogStream"
- "logs:PutLogEvents"
- "logs:GetLogEvents"
- "logs:DescribeLogStreams"
Resource: "arn:aws:logs:*:*:*"
# Lambda to move logs from cloudwatch to Elasticsearch
LogsToElasticsearchLambda:
Type: AWS::Lambda::Function
Properties:
Description: "CloudWatch Logs to Amazon ES streaming"
Handler: "logsToElasticsearch.handler"
Role: !GetAtt LogsToElasticsearchLambdaExecutionRole.Arn
Code:
S3Bucket: !Join
- ""
- - !ImportValue LambdaCodeBucket
S3Key: "lambdas/logsToElasticsearch.zip"
Environment:
Variables:
ELASTICSEARCH_ENDPOINT: !GetAtt SiteElasticsearch.DomainEndpoint
Timeout: 60
Runtime: nodejs6.10
# Lambda Elasticsearch Execution Instance profile
LambdaElasticsearchExecutionInstanceProfile:
Type: "AWS::IAM::InstanceProfile"
Properties:
Path: /
Roles:
- !Ref LogsToElasticsearchLambdaExecutionRole
# Permission to invoke Lambda to move Cloudwatch logs to Elasticsearch.
PermissionForCloudwatchLogsToInvokeLambda:
Type: "AWS::Lambda::Permission"
Properties:
FunctionName: !Ref LogsToElasticsearchLambda
Action: "lambda:InvokeFunction"
Principal: !Sub "logs.${AWS::Region}.amazonaws.com"
SourceArn: !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:*"
# Cloudwatch logs filter
SubscriptionFilter:
Type: "AWS::Logs::SubscriptionFilter"
Properties:
LogGroupName: !Ref SiteLogGroup
FilterPattern: "[bucketOwner, bucket, timestamp, ip, requester, requesterId, operation, key, requesturi, httpStatus=4*, errorCode, byteSent, objectSize, totalTime, turnaroundTime, referrer, userAgent, versionId]"
DestinationArn: !GetAtt LogsToElasticsearchLambda.Arn
DependsOn: PermissionForCloudwatchLogsToInvokeLambda
# Cloudwatch Cloudfront logs filter
CFSubscriptionFilter:
Type: "AWS::Logs::SubscriptionFilter"
Properties:
LogGroupName: !Ref CloudfrontLogGroup
FilterPattern: "[date, time, xedgelocation, scbytes, cip, csmethod, csHost, csuristem, scstatus, csReferer, csUserAgent, csuriquery, csCookie, xedgeresulttype, xedgerequestid, xhostheader, csprotocol, csbytes, timetaken, xforwardedfor, sslprotocol, sslcipher, xedgeresponseresulttype, csprotocolversion, flestatus, fleencryptedfields]"
DestinationArn: !GetAtt LogsToElasticsearchLambda.Arn
DependsOn: PermissionForCloudwatchLogsToInvokeLambda
# Role for DeleteIndice Lambda to delete logs from Elasticsearch
DeleteESIndexLambdaExecutionRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service: "lambda.amazonaws.com"
Action:
- "sts:AssumeRole"
Path: /
Policies:
- PolicyName: "root"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- "logs:CreateLogGroup"
- "logs:CreateLogStream"
- "logs:PutLogEvents"
Resource: "arn:aws:logs:*:*:*"
- Effect: "Allow"
Action:
- "es:*"
Resource: "arn:aws:es:*:*:*"
# Permission for cloudwatch to invoke lambda which will delete elasticsearch indices
PermissionForScheduledRuleToInvokeLambda:
Type: "AWS::Lambda::Permission"
Properties:
FunctionName: !Ref DeleteIndiceJobLambda
Action: "lambda:InvokeFunction"
Principal: "events.amazonaws.com"
SourceArn: !GetAtt OnceADayScheduledRule.Arn
# Rule for delete indice Lambda
OnceADayScheduledRule:
Type: "AWS::Events::Rule"
Properties:
Name: !Sub "once-a-day-${ProjectName}"
Description: "execute once a day"
State: "ENABLED"
ScheduleExpression: "rate(1 day)"
Targets:
- Arn: !GetAtt DeleteIndiceJobLambda.Arn
Id: "DeleteIndiceJobLambda"
# Delete Indice Lambda
DeleteIndiceJobLambda:
Type: "AWS::Lambda::Function"
Properties:
Code:
S3Bucket: !Join
- ""
- - !ImportValue LambdaCodeBucket
S3Key: "lambdas/deleteElasticSearchIndices.zip"
Description: "keep elasticsearch only 30 days indices for free tier"
Environment:
Variables:
ELASTICSEARCH_ENDPOINT: !GetAtt SiteElasticsearch.DomainEndpoint
DAYS_TOKEEP: !Ref ESIndexExpirationinDays
Handler: "deleteElasticSearchIndices.handler"
Role: !GetAtt DeleteESIndexLambdaExecutionRole.Arn
Runtime: nodejs6.10
Timeout: 30
# Lambda instance profile
DeleteESindexLambdaExecutionInstanceProfile:
Type: "AWS::IAM::InstanceProfile"
Properties:
Path: /
Roles:
- !Ref DeleteESIndexLambdaExecutionRole
# Creates a user pool in cognito for your app to auth against
CognitoUserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: !Sub "KibanaUsers${ProjectName}"
AdminCreateUserConfig:
AllowAdminCreateUserOnly: true
UsernameAttributes:
- email
AutoVerifiedAttributes:
- email
Policies:
PasswordPolicy:
MinimumLength: 8
Schema:
- Name: email
AttributeDataType: String
DeveloperOnlyAttribute: false
Mutable: true
Required: true
# Creates a federated Identity pool
CognitoIdentityPool:
Type: AWS::Cognito::IdentityPool
Properties:
IdentityPoolName: !Sub "KibanaIDPool${ProjectName}"
AllowUnauthenticatedIdentities: true
# CognitoIdentityProviders:
# - ClientId: !Ref UserPoolClient
# ProviderName: !Sub "cognito-idp.${AWS::Region}.amazonaws.com/${UserPool}"
# Cognito policy to access ElasticSearch
CognitoAuthenticatedPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- "es:ESHttp*"
- "mobileanalytics:PutEvents"
- "cognito-sync:*"
- "cognito-identity:*"
Resource:
- "*"
# Create a role for authorized acces to AWS resources. Control what your user can access. This example only allows Lambda invocation
# Only allows users in the previously created Identity Pool
CognitoAuthenticatedRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: "sts:AssumeRoleWithWebIdentity"
Principal:
Federated: cognito-identity.amazonaws.com
Condition:
StringEquals:
"cognito-identity.amazonaws.com:aud": !Ref CognitoIdentityPool
ForAnyValue:StringLike:
"cognito-identity.amazonaws.com:amr": authenticated
ManagedPolicyArns:
- !Ref CognitoAuthenticatedPolicy
# Create a role for unauthorized acces to AWS resources. Very limited access. Only allows users in the previously created Identity Pool
CognitoUnAuthenticatedRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Federated: "cognito-identity.amazonaws.com"
Action:
- "sts:AssumeRoleWithWebIdentity"
Condition:
StringEquals:
"cognito-identity.amazonaws.com:aud": !Ref CognitoIdentityPool
ForAnyValue:StringLike:
"cognito-identity.amazonaws.com:amr": unauthenticated
Policies:
- PolicyName: "CognitoUnauthorizedPolicy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"