-
Notifications
You must be signed in to change notification settings - Fork 879
/
index.ts
317 lines (273 loc) · 12.7 KB
/
index.ts
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
// Copyright 2016-2019, Pulumi Corporation. All rights reserved.
import * as aws from "@pulumi/aws";
import * as pulumi from "@pulumi/pulumi";
import * as fs from "fs";
import * as mime from "mime";
import * as path from "path";
import { configureACL } from "./acl";
// Load the Pulumi program configuration. These act as the "parameters" to the Pulumi program,
// so that different Pulumi Stacks can be brought up using the same code.
const stackConfig = new pulumi.Config();
const config = {
// pathToWebsiteContents is a relativepath to the website's contents.
pathToWebsiteContents: stackConfig.require("pathToWebsiteContents"),
// targetDomain is the domain/host to serve content at.
targetDomain: stackConfig.require("targetDomain"),
// (Optional) ACM certificate ARN for the target domain; must be in the us-east-1 region. If omitted, an ACM certificate will be created.
certificateArn: stackConfig.get("certificateArn"),
// If true create an A record for the www subdomain of targetDomain pointing to the generated cloudfront distribution.
// If a certificate was generated it will support this subdomain.
// default: true
includeWWW: stackConfig.getBoolean("includeWWW") ?? true,
};
// contentBucket is the S3 bucket that the website's contents will be stored in.
const contentBucket = new aws.s3.BucketV2(`${config.targetDomain}-content`);
const contentBucketWebsite = new aws.s3.BucketWebsiteConfigurationV2("contentBucketWebsite", {
bucket: contentBucket.bucket,
indexDocument: {suffix: "index.html"},
errorDocument: {key: "404.html"},
});
// crawlDirectory recursive crawls the provided directory, applying the provided function
// to every file it contains. Doesn't handle cycles from symlinks.
function crawlDirectory(dir: string, f: (_: string) => void) {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = `${dir}/${file}`;
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
crawlDirectory(filePath, f);
}
if (stat.isFile()) {
f(filePath);
}
}
}
// Sync the contents of the source directory with the S3 bucket, which will in-turn show up on the CDN.
const webContentsRootPath = path.join(process.cwd(), config.pathToWebsiteContents);
console.log("Syncing contents from local disk at", webContentsRootPath);
crawlDirectory(
webContentsRootPath,
(filePath: string) => {
const relativeFilePath = filePath.replace(webContentsRootPath + "/", "");
const contentFile = new aws.s3.BucketObject(
relativeFilePath,
{
key: relativeFilePath,
bucket: contentBucket.bucket,
contentType: mime.getType(filePath) || undefined,
source: new pulumi.asset.FileAsset(filePath),
},
{
parent: contentBucket,
});
});
// logsBucket is an S3 bucket that will contain the CDN's request logs.
const logsBucket = new aws.s3.BucketV2(`${config.targetDomain}-logs`);
configureACL("requestLogs", logsBucket, "private");
const tenMinutes = 60 * 10;
let certificateArn: pulumi.Input<string> = config.certificateArn!;
/**
* Only provision a certificate (and related resources) if a certificateArn is _not_ provided via configuration.
*/
if (!config.certificateArn) {
const eastRegion = new aws.Provider("east", {
profile: aws.config.profile,
region: "us-east-1", // Per AWS, ACM certificate must be in the us-east-1 region.
});
// if config.includeWWW include required subjectAlternativeNames to support the www subdomain
const certificateConfig: aws.acm.CertificateArgs = {
domainName: config.targetDomain,
validationMethod: "DNS",
subjectAlternativeNames: config.includeWWW ? [`www.${config.targetDomain}`] : [],
};
const certificate = new aws.acm.Certificate("certificate", certificateConfig, { provider: eastRegion });
const domainParts = getDomainAndSubdomain(config.targetDomain);
const hostedZoneId = aws.route53.getZone({ name: domainParts.parentDomain }, { async: true }).then(zone => zone.zoneId);
/**
* Create a DNS record to prove that we _own_ the domain we're requesting a certificate for.
* See https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-validate-dns.html for more info.
*/
const certificateValidationDomain = new aws.route53.Record(`${config.targetDomain}-validation`, {
name: certificate.domainValidationOptions[0].resourceRecordName,
zoneId: hostedZoneId,
type: certificate.domainValidationOptions[0].resourceRecordType,
records: [certificate.domainValidationOptions[0].resourceRecordValue],
ttl: tenMinutes,
});
// if config.includeWWW ensure we validate the www subdomain as well
let subdomainCertificateValidationDomain;
if (config.includeWWW) {
subdomainCertificateValidationDomain = new aws.route53.Record(`${config.targetDomain}-validation2`, {
name: certificate.domainValidationOptions[1].resourceRecordName,
zoneId: hostedZoneId,
type: certificate.domainValidationOptions[1].resourceRecordType,
records: [certificate.domainValidationOptions[1].resourceRecordValue],
ttl: tenMinutes,
});
}
// if config.includeWWW include the validation record for the www subdomain
const validationRecordFqdns = subdomainCertificateValidationDomain === undefined ?
[certificateValidationDomain.fqdn] : [certificateValidationDomain.fqdn, subdomainCertificateValidationDomain.fqdn];
/**
* This is a _special_ resource that waits for ACM to complete validation via the DNS record
* checking for a status of "ISSUED" on the certificate itself. No actual resources are
* created (or updated or deleted).
*
* See https://www.terraform.io/docs/providers/aws/r/acm_certificate_validation.html for slightly more detail
* and https://github.com/terraform-providers/terraform-provider-aws/blob/master/aws/resource_aws_acm_certificate_validation.go
* for the actual implementation.
*/
const certificateValidation = new aws.acm.CertificateValidation("certificateValidation", {
certificateArn: certificate.arn,
validationRecordFqdns: validationRecordFqdns,
}, { provider: eastRegion });
certificateArn = certificateValidation.certificateArn;
}
// Generate Origin Access Identity to access the private s3 bucket.
const originAccessIdentity = new aws.cloudfront.OriginAccessIdentity("originAccessIdentity", {
comment: "this is needed to setup s3 polices and make s3 not public.",
});
// if config.includeWWW include an alias for the www subdomain
const distributionAliases = config.includeWWW ? [config.targetDomain, `www.${config.targetDomain}`] : [config.targetDomain];
// distributionArgs configures the CloudFront distribution. Relevant documentation:
// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html
// https://www.terraform.io/docs/providers/aws/r/cloudfront_distribution.html
const distributionArgs: aws.cloudfront.DistributionArgs = {
enabled: true,
// Alternate aliases the CloudFront distribution can be reached at, in addition to https://xxxx.cloudfront.net.
// Required if you want to access the distribution via config.targetDomain as well.
aliases: distributionAliases,
// We only specify one origin for this distribution, the S3 content bucket.
origins: [
{
originId: contentBucket.arn,
domainName: contentBucket.bucketRegionalDomainName,
s3OriginConfig: {
originAccessIdentity: originAccessIdentity.cloudfrontAccessIdentityPath,
},
},
],
defaultRootObject: "index.html",
// A CloudFront distribution can configure different cache behaviors based on the request path.
// Here we just specify a single, default cache behavior which is just read-only requests to S3.
defaultCacheBehavior: {
targetOriginId: contentBucket.arn,
viewerProtocolPolicy: "redirect-to-https",
allowedMethods: ["GET", "HEAD", "OPTIONS"],
cachedMethods: ["GET", "HEAD", "OPTIONS"],
forwardedValues: {
cookies: { forward: "none" },
queryString: false,
},
minTtl: 0,
defaultTtl: tenMinutes,
maxTtl: tenMinutes,
},
// "All" is the most broad distribution, and also the most expensive.
// "100" is the least broad, and also the least expensive.
priceClass: "PriceClass_100",
// You can customize error responses. When CloudFront receives an error from the origin (e.g. S3 or some other
// web service) it can return a different error code, and return the response for a different resource.
customErrorResponses: [
{ errorCode: 404, responseCode: 404, responsePagePath: "/404.html" },
],
restrictions: {
geoRestriction: {
restrictionType: "none",
},
},
viewerCertificate: {
acmCertificateArn: certificateArn, // Per AWS, ACM certificate must be in the us-east-1 region.
sslSupportMethod: "sni-only",
},
loggingConfig: {
bucket: logsBucket.bucketDomainName,
includeCookies: false,
prefix: `${config.targetDomain}/`,
},
};
const cdn = new aws.cloudfront.Distribution("cdn", distributionArgs);
// Split a domain name into its subdomain and parent domain names.
// e.g. "www.example.com" => "www", "example.com".
function getDomainAndSubdomain(domain: string): { subdomain: string, parentDomain: string } {
const parts = domain.split(".");
if (parts.length < 2) {
throw new Error(`No TLD found on ${domain}`);
}
// No subdomain, e.g. awesome-website.com.
if (parts.length === 2) {
return { subdomain: "", parentDomain: domain };
}
const subdomain = parts[0];
parts.shift(); // Drop first element.
return {
subdomain,
// Trailing "." to canonicalize domain.
parentDomain: parts.join(".") + ".",
};
}
// Creates a new Route53 DNS record pointing the domain to the CloudFront distribution.
function createAliasRecord(
targetDomain: string, distribution: aws.cloudfront.Distribution): aws.route53.Record {
const domainParts = getDomainAndSubdomain(targetDomain);
const hostedZoneId = aws.route53.getZone({ name: domainParts.parentDomain }, { async: true }).then(zone => zone.zoneId);
return new aws.route53.Record(
targetDomain,
{
name: domainParts.subdomain,
zoneId: hostedZoneId,
type: "A",
aliases: [
{
name: distribution.domainName,
zoneId: distribution.hostedZoneId,
evaluateTargetHealth: true,
},
],
});
}
function createWWWAliasRecord(targetDomain: string, distribution: aws.cloudfront.Distribution): aws.route53.Record {
const domainParts = getDomainAndSubdomain(targetDomain);
const hostedZoneId = aws.route53.getZone({ name: domainParts.parentDomain }, { async: true }).then(zone => zone.zoneId);
return new aws.route53.Record(
`${targetDomain}-www-alias`,
{
name: `www.${targetDomain}`,
zoneId: hostedZoneId,
type: "A",
aliases: [
{
name: distribution.domainName,
zoneId: distribution.hostedZoneId,
evaluateTargetHealth: true,
},
],
},
);
}
const bucketPolicy = new aws.s3.BucketPolicy("bucketPolicy", {
bucket: contentBucket.id, // refer to the bucket created earlier
policy: pulumi.jsonStringify({
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Principal: {
AWS: originAccessIdentity.iamArn,
}, // Only allow Cloudfront read access.
Action: ["s3:GetObject"],
Resource: [pulumi.interpolate `${contentBucket.arn}/*`], // Give Cloudfront access to the entire bucket.
},
],
},
)});
const aRecord = createAliasRecord(config.targetDomain, cdn);
if (config.includeWWW) {
const cnameRecord = createWWWAliasRecord(config.targetDomain, cdn);
}
// Export properties from this stack. This prints them at the end of `pulumi up` and
// makes them easier to access from pulumi.com.
export const contentBucketUri = pulumi.interpolate`s3://${contentBucket.bucket}`;
export const contentBucketWebsiteEndpoint = contentBucketWebsite.websiteEndpoint;
export const cloudFrontDomain = cdn.domainName;
export const targetDomainEndpoint = `https://${config.targetDomain}/`;