-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathspa-deploy-construct.ts
More file actions
296 lines (257 loc) · 10.7 KB
/
spa-deploy-construct.ts
File metadata and controls
296 lines (257 loc) · 10.7 KB
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
import {
CloudFrontWebDistribution,
ViewerCertificate,
OriginAccessIdentity,
Behavior,
SSLMethod,
SecurityPolicyProtocol,
} from '@aws-cdk/aws-cloudfront';
import { PolicyStatement, Role, AnyPrincipal, Effect } from '@aws-cdk/aws-iam';
import { HostedZone, ARecord, RecordTarget } from '@aws-cdk/aws-route53';
import { DnsValidatedCertificate } from '@aws-cdk/aws-certificatemanager';
import { HttpsRedirect } from '@aws-cdk/aws-route53-patterns';
import { CloudFrontTarget } from '@aws-cdk/aws-route53-targets';
import cdk = require('@aws-cdk/core');
import s3deploy= require('@aws-cdk/aws-s3-deployment');
import s3 = require('@aws-cdk/aws-s3');
import { RemovalPolicy } from '@aws-cdk/core';
export interface SPADeployConfig {
readonly indexDoc:string,
readonly errorDoc?:string,
readonly websiteFolder: string,
readonly certificateARN?: string,
readonly cfBehaviors?: Behavior[],
readonly cfAliases?: string[],
readonly exportWebsiteUrlOutput?:boolean,
readonly exportWebsiteUrlName?: string,
readonly blockPublicAccess?:s3.BlockPublicAccess
readonly sslMethod?: SSLMethod,
readonly securityPolicy?: SecurityPolicyProtocol,
readonly role?:Role,
readonly bucketRemovalPolicy?: RemovalPolicy,
}
export interface HostedZoneConfig extends Partial<SPADeployConfig> {
readonly indexDoc:string,
readonly errorDoc?:string,
readonly cfBehaviors?: Behavior[],
readonly websiteFolder: string,
readonly zoneName: string,
readonly subdomain?: string,
readonly role?: Role,
}
export interface SPAGlobalConfig {
readonly encryptBucket?:boolean,
readonly ipFilter?:boolean,
readonly ipList?:string[],
readonly role?:Role,
}
export interface SPADeployment {
readonly websiteBucket: s3.Bucket,
}
export interface SPADeploymentWithCloudFront extends SPADeployment {
readonly distribution: CloudFrontWebDistribution,
}
export class SPADeploy extends cdk.Construct {
globalConfig: SPAGlobalConfig;
constructor(scope: cdk.Construct, id:string, config?:SPAGlobalConfig) {
super(scope, id);
if (typeof config !== 'undefined') {
this.globalConfig = config;
} else {
this.globalConfig = {
encryptBucket: false,
ipFilter: false,
};
}
}
/**
* Helper method to provide a configured s3 bucket
*/
private getS3Bucket(config:SPADeployConfig, isForCloudFront: boolean) {
const bucketConfig:any = {
websiteIndexDocument: config.indexDoc,
websiteErrorDocument: config.errorDoc,
publicReadAccess: true,
};
if (this.globalConfig.encryptBucket === true) {
bucketConfig.encryption = s3.BucketEncryption.S3_MANAGED;
}
if (this.globalConfig.ipFilter === true || isForCloudFront === true) {
bucketConfig.publicReadAccess = false;
if (typeof config.blockPublicAccess !== 'undefined') {
bucketConfig.blockPublicAccess = config.blockPublicAccess;
}
}
if (config.bucketRemovalPolicy) {
bucketConfig.removalPolicy = config.bucketRemovalPolicy;
}
if (config.bucketRemovalPolicy === RemovalPolicy.DESTROY) {
bucketConfig.autoDeleteObjects = true;
}
const bucket = new s3.Bucket(this, 'WebsiteBucket', bucketConfig);
if (this.globalConfig.ipFilter === true && isForCloudFront === false) {
if (typeof this.globalConfig.ipList === 'undefined') {
this.node.addError('When IP Filter is true then the IP List is required');
}
const bucketPolicy = new PolicyStatement();
bucketPolicy.addAnyPrincipal();
bucketPolicy.addActions('s3:GetObject');
bucketPolicy.addResources(`${bucket.bucketArn}/*`);
bucketPolicy.addCondition('IpAddress', {
'aws:SourceIp': this.globalConfig.ipList,
});
bucket.addToResourcePolicy(bucketPolicy);
}
//The below "reinforces" the IAM Role's attached policy, it's not required but it allows for customers using permission boundaries to write into the bucket.
if (config.role) {
bucket.addToResourcePolicy(
new PolicyStatement({
actions: [
"s3:GetObject*",
"s3:GetBucket*",
"s3:List*",
"s3:DeleteObject*",
"s3:PutObject*",
"s3:Abort*"
],
effect: Effect.ALLOW,
resources: [bucket.arnForObjects('*'), bucket.bucketArn],
conditions: {
StringEquals: {
'aws:PrincipalArn': config.role.roleArn,
},
},
principals: [new AnyPrincipal()]
})
);
}
return bucket;
}
/**
* Helper method to provide configuration for cloudfront
*/
private getCFConfig(websiteBucket:s3.Bucket, config:any, accessIdentity: OriginAccessIdentity, cert?:DnsValidatedCertificate) {
const cfConfig:any = {
originConfigs: [
{
s3OriginSource: {
s3BucketSource: websiteBucket,
originAccessIdentity: accessIdentity,
},
behaviors: config.cfBehaviors ? config.cfBehaviors : [{ isDefaultBehavior: true }],
},
],
// We need to redirect all unknown routes back to index.html for angular routing to work
errorConfigurations: [{
errorCode: 403,
responsePagePath: (config.errorDoc ? `/${config.errorDoc}` : `/${config.indexDoc}`),
responseCode: 200,
},
{
errorCode: 404,
responsePagePath: (config.errorDoc ? `/${config.errorDoc}` : `/${config.indexDoc}`),
responseCode: 200,
}],
};
if (typeof config.certificateARN !== 'undefined' && typeof config.cfAliases !== 'undefined') {
cfConfig.aliasConfiguration = {
acmCertRef: config.certificateARN,
names: config.cfAliases,
};
}
if (typeof config.sslMethod !== 'undefined') {
cfConfig.aliasConfiguration.sslMethod = config.sslMethod;
}
if (typeof config.securityPolicy !== 'undefined') {
cfConfig.aliasConfiguration.securityPolicy = config.securityPolicy;
}
if (typeof config.zoneName !== 'undefined' && typeof cert !== 'undefined') {
cfConfig.viewerCertificate = ViewerCertificate.fromAcmCertificate(cert, {
aliases: [config.subdomain ? `${config.subdomain}.${config.zoneName}` : config.zoneName],
});
}
return cfConfig;
}
/**
* Basic setup needed for a non-ssl, non vanity url, non cached s3 website
*/
public createBasicSite(config:SPADeployConfig): SPADeployment {
const websiteBucket = this.getS3Bucket(config, false);
new s3deploy.BucketDeployment(this, 'BucketDeployment', {
sources: [s3deploy.Source.asset(config.websiteFolder)],
role: config.role,
destinationBucket: websiteBucket,
});
const cfnOutputConfig:any = {
description: 'The url of the website',
value: websiteBucket.bucketWebsiteUrl,
};
if (config.exportWebsiteUrlOutput === true) {
if (typeof config.exportWebsiteUrlName === 'undefined' || config.exportWebsiteUrlName === '') {
this.node.addError('When Output URL as AWS Export property is true then the output name is required');
}
cfnOutputConfig.exportName = config.exportWebsiteUrlName;
}
new cdk.CfnOutput(this, 'URL', cfnOutputConfig);
return { websiteBucket };
}
/**
* This will create an s3 deployment fronted by a cloudfront distribution
* It will also setup error forwarding and unauth forwarding back to indexDoc
*/
public createSiteWithCloudfront(config:SPADeployConfig): SPADeploymentWithCloudFront {
const websiteBucket = this.getS3Bucket(config, true);
const accessIdentity = new OriginAccessIdentity(this, 'OriginAccessIdentity', { comment: `${websiteBucket.bucketName}-access-identity` });
const distribution = new CloudFrontWebDistribution(this, 'cloudfrontDistribution', this.getCFConfig(websiteBucket, config, accessIdentity));
new s3deploy.BucketDeployment(this, 'BucketDeployment', {
sources: [s3deploy.Source.asset(config.websiteFolder)],
destinationBucket: websiteBucket,
// Invalidate the cache for / and index.html when we deploy so that cloudfront serves latest site
distribution,
distributionPaths: ['/', `/${config.indexDoc}`],
role: config.role,
});
new cdk.CfnOutput(this, 'cloudfront domain', {
description: 'The domain of the website',
value: distribution.distributionDomainName,
});
return { websiteBucket, distribution };
}
/**
* S3 Deployment, cloudfront distribution, ssl cert and error forwarding auto
* configured by using the details in the hosted zone provided
*/
public createSiteFromHostedZone(config:HostedZoneConfig): SPADeploymentWithCloudFront {
const websiteBucket = this.getS3Bucket(config, true);
const zone = HostedZone.fromLookup(this, 'HostedZone', { domainName: config.zoneName });
const domainName = config.subdomain ? `${config.subdomain}.${config.zoneName}` : config.zoneName;
const cert = new DnsValidatedCertificate(this, 'Certificate', {
hostedZone: zone,
domainName,
region: 'us-east-1',
});
const accessIdentity = new OriginAccessIdentity(this, 'OriginAccessIdentity', { comment: `${websiteBucket.bucketName}-access-identity` });
const distribution = new CloudFrontWebDistribution(this, 'cloudfrontDistribution', this.getCFConfig(websiteBucket, config, accessIdentity, cert));
new s3deploy.BucketDeployment(this, 'BucketDeployment', {
sources: [s3deploy.Source.asset(config.websiteFolder)],
destinationBucket: websiteBucket,
// Invalidate the cache for / and index.html when we deploy so that cloudfront serves latest site
distribution,
role: config.role,
distributionPaths: ['/', `/${config.indexDoc}`],
});
new ARecord(this, 'Alias', {
zone,
recordName: domainName,
target: RecordTarget.fromAlias(new CloudFrontTarget(distribution)),
});
if (!config.subdomain) {
new HttpsRedirect(this, 'Redirect', {
zone,
recordNames: [`www.${config.zoneName}`],
targetDomain: config.zoneName,
});
}
return { websiteBucket, distribution };
}
}