forked from alestic/aws-git-backed-static-website
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcodepipeline-powered-static-website-cloudformation.yml
578 lines (542 loc) · 19.6 KB
/
codepipeline-powered-static-website-cloudformation.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
---
AWSTemplateFormatVersion: "2010-09-09"
Description: |
Static web site stack including:
* CodePipeline integrating:
* Source stage from either code-commit or github
* Build stage to run a buildspec (eg. upload the static website upon git commit)
* S3 bucket for web site content
* Redirect from "www." to base domain
* Access logs written to logs bucket
* ACM Certificate for SSL
* CloudFront distributions for website https access
* Route 53 hosted zone with DNS entries
* S3 bucket for CodePipeline artifacts
* SNS topic for CodeCommit Git change notifications
* Email address subscribed to SNS notification topic
Parameters:
# 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 (-)"
# Email address to receive Git activity notifications: you@anotherdomain.com
# CANNOT be in same domain!
NotificationEmail:
Type: String
Description: "Initial email address to receive Git change notifications"
MinLength: 6
AllowedPattern: ".+@[a-z0-9]+[-.a-z0-9]*(\\.[a-z][a-z]+)+"
ConstraintDescription: "Provide a valid email address"
DefaultTTL:
Type: Number
Description: "TTL in seconds"
Default: 50000
MinimumTTL:
Description: "Minimum cache lifetime in seconds for the CloudFront distribution"
Default: 60
Type: Number
PriceClass:
Description: "Distribution 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
SourceType:
Description: "CodeCommit | GitHub"
Type: String
Default: "CodeCommit"
AllowedValues:
- CodeCommit
- GitHub
BranchName:
Description: "Name of branch to build from"
Type: String
Default: master
GithubOauthToken:
Type: String
NoEcho: true
Description: "For Github integrations this is necessary. Otherwise leave blank."
GithubRepoOwner:
Type: String
Description: "For Github integrations this is necessary. Otherwise leave blank."
GithubRepoName:
Type: String
Description: "For Github integrations this is necessary. Otherwise leave blank."
BuildEnvironmentImage:
Description: "Optional image to use for codebuild eg. docker:dind defaults to a ruby environment suitable for Jekyll builds."
Type: String
Default: "aws/codebuild/ruby:2.3.1"
PreExistingGitRepository:
Description: "Optional Git repository name for pre-existing git repository. Leave empty to have CodeCommit Repository created and managed by this stack."
Type: String
Default: ""
PreExistingHostedZoneDomain:
Description: "Optional domain name for pre-existing Route 53 hosted zone. Leave empty to have hosted zone created and managed by this stack."
Type: String
Default: ""
PreExistingSiteBucket:
Description: "Optional name of pre-existing website bucket. Leave empty to have website bucket created and managed by this stack."
Type: String
Default: ""
PreExistingRedirectBucket:
Description: "Optional name of pre-existing redirect bucket. Leave empty to have redirect bucket created and managed by this stack."
Type: String
Default: ""
PreExistingLogsBucket:
Description: "Optional name of pre-existing access logs bucket. Leave empty to have access logs bucket 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: ""
Conditions:
IsCodeCommit: !Equals [!Ref SourceType, "CodeCommit"]
NeedsNewGitRepository: !And [!Equals [!Ref PreExistingGitRepository, ""], !Equals [!Ref SourceType, "CodeCommit"]]
NeedsNewHostedZone: !Equals [!Ref PreExistingHostedZoneDomain, ""]
NeedsNewSiteBucket: !Equals [!Ref PreExistingSiteBucket, ""]
NeedsNewRedirectBucket: !Equals [!Ref PreExistingRedirectBucket, ""]
NeedsNewLogsBucket: !Equals [!Ref PreExistingLogsBucket, ""]
NeedsNewCodePipelineBucket: !Equals [!Ref PreExistingCodePipelineBucket, ""]
Resources:
# Bucket for CloudFront and S3 access logs: logs.example.com
LogsBucket:
Condition: NeedsNewLogsBucket
Type: "AWS::S3::Bucket"
Properties:
BucketName: !Sub "logs.${DomainName}"
AccessControl: LogDeliveryWrite
DeletionPolicy: Retain
# Bucket for site content: example.com
SiteBucket:
Condition: NeedsNewSiteBucket
Type: "AWS::S3::Bucket"
Properties:
BucketName: !Ref DomainName
AccessControl: PublicRead
WebsiteConfiguration:
IndexDocument: index.html
ErrorDocument: 404.html
# logs.example.com/logs/s3/example.com/
LoggingConfiguration:
DestinationBucketName: !If [NeedsNewLogsBucket, !Ref LogsBucket, !Ref PreExistingLogsBucket]
LogFilePrefix: !Sub "logs/s3/${DomainName}/"
DeletionPolicy: Retain
# bucket policy to provide read access to assets in SiteBucket
SiteBucketPolicy:
Type: "AWS::S3::BucketPolicy"
Properties:
Bucket: !If [NeedsNewSiteBucket, !Ref SiteBucket, !Ref PreExistingSiteBucket]
PolicyDocument:
Statement:
-
Action:
- "s3:GetObject"
Effect: "Allow"
Resource:
- !Join ["",
[
"arn:aws:s3:::",
!If [
NeedsNewSiteBucket,
!Ref SiteBucket,
!Ref PreExistingSiteBucket
],
"/*"
],
]
Principal: "*"
# 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 CodePipeline artifact storage: codepipeline.example.com
CodePipelineBucket:
Condition: NeedsNewCodePipelineBucket
Type: "AWS::S3::Bucket"
Properties:
BucketName: !Sub "codepipeline.${DomainName}"
VersioningConfiguration:
Status: Enabled
DeletionPolicy: Retain
# Certificate for HTTPS accesss through CloudFront
Certificate:
Type: "AWS::CertificateManager::Certificate"
Properties:
DomainName: !Ref DomainName
SubjectAlternativeNames:
- !Sub "www.${DomainName}"
# 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: !Ref Certificate
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: !Ref Certificate
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: Retain
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
# SNS topic for Git repository activity. Email subscription
NotificationTopic:
Type: "AWS::SNS::Topic"
Properties:
DisplayName: !Sub "Activity in ${DomainName} Git repository"
Subscription:
- Endpoint: !Ref NotificationEmail
Protocol: email
# Git repository: example.com
GitRepository:
Condition: NeedsNewGitRepository
Type: "AWS::CodeCommit::Repository"
Properties:
RepositoryDescription: !Sub "Git repository for ${DomainName}"
RepositoryName: !Ref DomainName
Triggers:
- Name: !Sub "Activity in ${DomainName} Git repository"
DestinationArn: !Ref NotificationTopic
Events:
- all
DeletionPolicy: Retain
# IAM info for AWS Lambda functions
CodeBuildExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
Effect: Allow
Principal:
Service: codebuild.amazonaws.com
Action: sts:AssumeRole
Version: '2012-10-17'
Path: "/"
Policies:
- PolicyName: !Sub "${DomainName}-codebuild-policy"
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: "logs:*"
Resource: "arn:aws:logs:*:*:*"
- Effect: Allow
Action:
- s3:*
Resource:
- !Join ["", ["arn:aws:s3:::", !If [NeedsNewSiteBucket, !Ref SiteBucket, !Ref PreExistingSiteBucket], "/*"]]
- !Join ["", ["arn:aws:s3:::", !If [NeedsNewCodePipelineBucket, !Ref CodePipelineBucket, !Ref PreExistingCodePipelineBucket], "/*"]]
# IAM info for CodePipeline
CodePipelineRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- "codebuild.amazonaws.com"
- "codepipeline.amazonaws.com"
Action:
- "sts:AssumeRole"
Path: "/"
Policies:
- PolicyName: "codepipeline-service"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action: "*"
Resource: "*"
BuildCopySourceProject:
Type: AWS::CodeBuild::Project
Properties:
Name: !Sub BuildCopySource-${AWS::StackName}
Description: Build static site and copy to s3
ServiceRole: !GetAtt CodeBuildExecutionRole.Arn
Environment:
Type: LINUX_CONTAINER
ComputeType: BUILD_GENERAL1_SMALL
Image: !Ref BuildEnvironmentImage
EnvironmentVariables:
- Name: TARGET_S3_BUCKET
Value: !Join ["", ["s3://", !If [NeedsNewSiteBucket, !Ref SiteBucket, !Ref PreExistingSiteBucket]]]
Source:
Type: CODEPIPELINE
Artifacts:
Type: CODEPIPELINE
TimeoutInMinutes: 15
EncryptionKey: !Sub arn:aws:kms:${AWS::Region}:${AWS::AccountId}:alias/aws/s3
Tags:
- Key: Name
Value: !Sub BuildCopySource-${AWS::StackName}
# CodePipeline: Pass Git contents to AWS Lambda function on Git activity
CodePipeline:
Type: "AWS::CodePipeline::Pipeline"
Properties:
Name: !Sub "${DomainName}-codepipeline"
ArtifactStore:
Type: S3
Location: !If [NeedsNewCodePipelineBucket, !Ref CodePipelineBucket, !Ref PreExistingCodePipelineBucket]
RestartExecutionOnUpdate: false
RoleArn: !Sub "arn:aws:iam::${AWS::AccountId}:role/${CodePipelineRole}"
Stages:
- Name: Source
Actions:
- Name: SourceAction
ActionTypeId:
Category: Source
Owner: !If [IsCodeCommit, "AWS", "ThirdParty"]
Provider: !Ref SourceType
Version: 1
Configuration:
!If
- IsCodeCommit
-
RepositoryName: !If [NeedsNewGitRepository, !Ref DomainName, !Ref PreExistingGitRepository]
BranchName: !Ref BranchName
-
Owner: !Ref GithubRepoOwner
Repo: !Ref GithubRepoName
Branch: !Ref BranchName
OAuthToken: !Ref GithubOauthToken
OutputArtifacts:
- Name: SiteSource
RunOrder: 1
- Name: MakeWebsite
Actions:
- Name: Build
InputArtifacts:
- Name: SiteSource
ActionTypeId:
Category: Build
Owner: AWS
Version: 1
Provider: CodeBuild
Configuration:
ProjectName:
Ref: BuildCopySourceProject
RunOrder: 1
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"
websiteendpoint: "s3-website-us-west-2.amazonaws.com"
Outputs:
DomainName:
Description: Domain name
Value: !Ref DomainName
RedirectDomainName:
Description: Redirect hostname
Value: !If [NeedsNewRedirectBucket, !Ref RedirectBucket, !Ref PreExistingRedirectBucket]
SiteBucket:
Value: !If [NeedsNewSiteBucket, !Ref SiteBucket, !Ref PreExistingSiteBucket]
RedirectBucket:
Value: !If [NeedsNewRedirectBucket, !Ref RedirectBucket, !Ref PreExistingRedirectBucket]
LogsBucket:
Description: S3 Bucket with access logs
Value: !If [NeedsNewLogsBucket, !Ref LogsBucket, !Ref PreExistingLogsBucket]
HostedZoneId:
Description: Route 53 Hosted Zone id
Value: !If [NeedsNewHostedZone, !Ref Route53HostedZone, "N/A"]
CloudFrontDomain:
Description: CloudFront distribution domain name
Value: !Ref CloudFrontDistribution
RedirectCloudFrontDomain:
Description: Redirect CloudFront distribution domain name
Value: !Ref RedirectCloudFrontDistribution
CodePipelineArn:
Description: CodePipeline ARN
Value: !Ref CodePipeline
GitRepositoryName:
Description: Git repository name
Value: !If [NeedsNewGitRepository, !Ref DomainName, !Ref PreExistingGitRepository]
GitCloneUrlHttp:
Description: Git https clone endpoint
Value: !If [NeedsNewGitRepository, !GetAtt GitRepository.CloneUrlHttp, "N/A"]
GitCloneUrlSsh:
Description: Git ssh clone endpoint
Value: !If [NeedsNewGitRepository, !GetAtt GitRepository.CloneUrlSsh, "N/A"]
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: Website
Parameters:
- DomainName
- Label:
default: Source Code Repository
Parameters:
- SourceType
- BranchName
- GithubRepoOwner
- GithubRepoName
- GithubOauthToken
- Label:
default: Git Activity
Parameters:
- NotificationEmail
- Label:
default: CodeBuild
Parameters:
- BuildEnvironmentImage
- Label:
default: CloudFront CDN
Parameters:
- PriceClass
- MinimumTTL
- DefaultTTL
- Label:
default: PreExisting Resources To Use (Leave empty for stack to create and manage)
Parameters:
- PreExistingGitRepository
- PreExistingHostedZoneDomain
- PreExistingSiteBucket
- PreExistingRedirectBucket
- PreExistingLogsBucket
- PreExistingCodePipelineBucket