/
static-website-infrastructure.yml
420 lines (398 loc) · 12.5 KB
/
static-website-infrastructure.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
---
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Static website hosting with S3 and CloudFront with a custom domain.'
Metadata:
'AWS::CloudFormation::Interface':
ParameterGroups:
- Label:
default: 'DNS'
Parameters:
- Domain
- HostedZoneID
- CreateCert
- Label:
default: 'Paths'
Parameters:
- ErrorPagePath
- IndexDocument
- Label:
default: 'Administrative'
Parameters:
- LogsRetentionInDays
- Label:
default: 'Version Control'
Parameters:
- RepositoryName
- RepositoryDescription
- BuildProjectName
Parameters:
Domain:
Description: 'The domain of your website.'
Type: String
HostedZoneID:
Description: 'The ID of your hosted zone in Route 53'
Type: 'AWS::Route53::HostedZone::Id'
CreateCert:
Description: 'Whether to create an HTTPS certificate for this site. You MUST create this stack in the us-east-1 (N. Virginia) region when creating a certificate'
Type: String
AllowedValues:
- 'Yes'
- 'No'
Default: 'Yes'
ErrorPagePath:
Description: 'The path of the error page for the website.'
Type: String
Default: '/404.html'
IndexDocument:
Description: 'Directory index filename'
Type: String
Default: 'index.html'
LogsRetentionInDays:
Description: 'Specifies the number of days you want to retain log events'
Type: Number
Default: 14
AllowedValues: [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653]
RepositoryName:
Description: 'Repository where the code for the website lives'
Type: String
Default: 'test.domain.com'
RepositoryDescription:
Description: 'Description of the repository'
Type: String
Default: 'My website'
BuildProjectName:
Description: 'Name of the build project'
Type: String
Default: 'my-website-build'
Conditions:
ShouldCreateCert: !Equals
- !Ref CreateCert
- 'Yes'
Resources:
# Create the bucket to contain the website HTML
S3Bucket:
Type: 'AWS::S3::Bucket'
# Create a CloudFront Access Identity to broker access to the bucket
CloudFrontOriginAccessIdentity:
Type: 'AWS::CloudFront::CloudFrontOriginAccessIdentity'
Properties:
CloudFrontOriginAccessIdentityConfig:
Comment: !Ref S3Bucket
ReadPolicy:
Type: 'AWS::S3::BucketPolicy'
Properties:
Bucket: !Ref S3Bucket
PolicyDocument:
Statement:
- Action: 's3:GetObject'
Effect: Allow
Resource: !Sub 'arn:aws:s3:::${S3Bucket}/*'
Principal:
CanonicalUser: !GetAtt CloudFrontOriginAccessIdentity.S3CanonicalUserId
# Configure the bucket as a CloudFront Origin and grant access via the access identity
CloudFrontDistribution:
Type: 'AWS::CloudFront::Distribution'
Properties:
DistributionConfig:
Aliases:
- !Ref Domain
ViewerCertificate:
AcmCertificateArn: !Ref Cert
SslSupportMethod: 'sni-only'
CustomErrorResponses:
- ErrorCode: 403 # not found
ResponseCode: 404
ResponsePagePath: !Ref ErrorPagePath
DefaultCacheBehavior:
AllowedMethods:
- GET
- HEAD
- OPTIONS
CachedMethods:
- GET
- HEAD
- OPTIONS
Compress: true
DefaultTTL: 3600 # in seconds
ForwardedValues:
Cookies:
Forward: none
QueryString: false
MaxTTL: 86400 # in seconds
MinTTL: 60 # in seconds
TargetOriginId: s3origin
ViewerProtocolPolicy: !If
- ShouldCreateCert
- 'redirect-to-https'
- 'allow-all'
LambdaFunctionAssociations:
- EventType: 'origin-request'
LambdaFunctionARN: !Ref LambdaVersionV1
DefaultRootObject: ''
Enabled: true
HttpVersion: http2
Origins:
- DomainName: !GetAtt 'S3Bucket.DomainName'
Id: s3origin
S3OriginConfig:
OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}'
PriceClass: 'PriceClass_All'
# Lambda@Edge function to handle doc root stuff
LambdaRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- 'lambda.amazonaws.com'
- 'edgelambda.amazonaws.com'
Action: 'sts:AssumeRole'
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
LambdaFunction:
Type: 'AWS::Lambda::Function'
Properties:
Code:
# If you change the ZipFile, rename the logical id LambdaVersionV1 to trigger a new version creation!
ZipFile: !Sub |
'use strict';
const regex = /\.[a-z0-9]+$/;
const indexDocument = '${IndexDocument}';
exports.handler = (event, context, cb) => {
const cf = event.Records[0].cf;
const config = cf.config;
const request = cf.request;
if (request.uri.endsWith('/')) {
cb(null, Object.assign({}, request, {uri: `${!request.uri}${!indexDocument}`}));
} else if (request.uri.endsWith(`/${!indexDocument}`)) {
cb(null, {
status: '302',
statusDescription: 'Found',
headers: {
location: [{
key: 'Location',
value: request.uri.substr(0, request.uri.length - indexDocument.length),
}],
}
});
} else if (!regex.test(request.uri)) {
cb(null, {
status: '302',
statusDescription: 'Found',
headers: {
location: [{
key: 'Location',
value: `${!request.uri}/`,
}],
}
});
} else {
cb(null, request);
}
};
Handler: 'index.handler'
MemorySize: 128
Role: !GetAtt 'LambdaRole.Arn'
Runtime: 'nodejs8.10'
Timeout: 5
LambdaLogGroup:
Type: 'AWS::Logs::LogGroup'
Properties:
LogGroupName: !Sub '/aws/lambda/${LambdaFunction}'
RetentionInDays: !Ref LogsRetentionInDays
LambdaVersionV1:
Type: 'AWS::Lambda::Version'
Properties:
FunctionName: !Ref LambdaFunction
# Lambda to trigger code builds on code push
CodeBuildLambdaRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- 'lambda.amazonaws.com'
Action: 'sts:AssumeRole'
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
- 'arn:aws:iam::aws:policy/AWSCodeBuildDeveloperAccess'
- 'arn:aws:iam::aws:policy/AmazonSQSFullAccess'
CodeBuildLambdaFunction:
Type: 'AWS::Lambda::Function'
Properties:
Code:
# If you change the ZipFile, rename the logical id CBLambdaVersionV1 to trigger a new version creation!
ZipFile: !Sub |
import boto3
import os
def entrypoint(event, context):
print('Starting a new build ...')
cb = boto3.client('codebuild')
build = {
'projectName': os.environ['project_name'],
}
cb.start_build(**build)
print('Successfully launched a new CodeBuild project build!')
Handler: 'index.entrypoint'
MemorySize: 128
Role: !GetAtt 'CodeBuildLambdaRole.Arn'
Runtime: 'python3.6'
Timeout: 5
Environment:
Variables:
'project_name': !Ref BuildProjectName
LambdaLogGroup:
Type: 'AWS::Logs::LogGroup'
Properties:
LogGroupName: !Sub '/aws/lambda/${CodeBuildLambdaFunction}'
RetentionInDays: !Ref LogsRetentionInDays
CBLambdaVersionV1:
Type: 'AWS::Lambda::Version'
Properties:
FunctionName: !Ref CodeBuildLambdaFunction
CodeBuildLambdaFunctionEventSourceMapping:
Type: AWS::Lambda::EventSourceMapping
Properties:
BatchSize: 10
Enabled: true
EventSourceArn: !GetAtt CodeRepositorySQS.Arn
FunctionName: !GetAtt CodeBuildLambdaFunction.Arn
# Set up A Record via Route 53
Route53Record:
Type: 'AWS::Route53::RecordSet'
Properties:
HostedZoneId: !Ref HostedZoneID
Name: !Ref Domain
Type: A
AliasTarget:
HostedZoneId: Z2FDTNDATAQYW2 # This Zone ID is used for any CloudFront Distribution
DNSName: !GetAtt 'CloudFrontDistribution.DomainName'
Route53AliasRecord:
Type: 'AWS::Route53::RecordSet'
Properties:
HostedZoneId: !Ref HostedZoneID
Name: !Sub 'www.${Domain}'
Type: CNAME
TTL: '900'
ResourceRecords:
- !Ref Domain
# Set up TLS Cert
Cert:
Condition: ShouldCreateCert
Type: 'AWS::CertificateManager::Certificate'
Properties:
DomainName: !Ref Domain
ValidationMethod: DNS
# Create an IAM user with Access Keys to enable automated deployment of the website to this bucket
PublishUser:
Type: 'AWS::IAM::User'
Properties:
Policies:
- PolicyName: !Sub 'publish-to-${S3Bucket}'
PolicyDocument:
Statement:
- Action: 's3:*'
Effect: Allow
Resource:
- !Sub 'arn:aws:s3:::${S3Bucket}'
- !Sub 'arn:aws:s3:::${S3Bucket}/*'
# Create SQS queue for CodeCommit events
CodeRepositorySQS:
Type: 'AWS::SQS::Queue'
# Create SNS topic for CodeCommit events
CodeRepositorySNS:
Type: 'AWS::SNS::Topic'
Properties:
Subscription:
- Endpoint: !GetAtt CodeRepositorySQS.Arn
Protocol: "sqs"
# SNS to SQS communication policy
CodeRepositorySNSToSQSPolicy:
Type: AWS::SQS::QueuePolicy
Properties:
Queues: [!Ref 'CodeRepositorySQS']
PolicyDocument:
Version: '2008-10-17'
Id: PublicationPolicy
Statement:
- Sid: Allow-SNS-SendMessage
Effect: Allow
Principal:
AWS: '*'
Action: ['sqs:SendMessage']
Resource: !GetAtt [CodeRepositorySQS, Arn]
Condition:
ArnEquals:
aws:SourceArn: !Ref 'CodeRepositorySNS'
# Create a git repository for the website code
CodeRepository:
Type: 'AWS::CodeCommit::Repository'
Properties:
RepositoryName: !Ref RepositoryName
RepositoryDescription: !Ref RepositoryDescription
Triggers:
- Name: SNSTrigger
DestinationArn: !Ref CodeRepositorySNS
Events:
- all
# Create the role for the build infrastructure
CodeBuildRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- 'codebuild.amazonaws.com'
Action: 'sts:AssumeRole'
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/AWSCodeBuildDeveloperAccess'
- 'arn:aws:iam::aws:policy/AmazonS3FullAccess'
- 'arn:aws:iam::aws:policy/CloudFrontFullAccess'
- 'arn:aws:iam::aws:policy/CloudWatchLogsFullAccess'
- 'arn:aws:iam::aws:policy/AWSCodeCommitPowerUser'
# Create the build infrastructure
CodeBuild:
Type: 'AWS::CodeBuild::Project'
Properties:
Name: !Ref BuildProjectName
Description: !Ref RepositoryDescription
ServiceRole: !GetAtt CodeBuildRole.Arn
BadgeEnabled: true
Artifacts:
Type: no_artifacts
Environment:
Type: LINUX_CONTAINER
ComputeType: BUILD_GENERAL1_SMALL
Image: aws/codebuild/ruby:2.5.3-1.7.0 # Change to a different image if not using Jekyll
Source:
Location: !GetAtt CodeRepository.CloneUrlHttp
Type: CODECOMMIT
TimeoutInMinutes: 10
Outputs:
BucketName:
Description: 'S3 Bucket Name'
Value: !Ref S3Bucket
PublishUser:
Description: 'IAM User with write access to the bucket'
Value: !Ref PublishUser
DistributionId:
Description: 'CloudFront Distribution ID'
Value: !Ref CloudFrontDistribution
CodeRepository:
Description: 'Code repository for website'
Value: !Ref CodeRepository
URL:
Description: 'URL of your website'
Value: !If
- ShouldCreateCert
- !Sub 'https://${Domain}'
- !Sub 'http://${Domain}'