/
website-bucket.ts
106 lines (91 loc) · 2.88 KB
/
website-bucket.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
import {
CfnCloudFrontOriginAccessIdentity,
S3OriginConfig,
} from '@aws-cdk/aws-cloudfront';
import { CanonicalUserPrincipal } from '@aws-cdk/aws-iam';
import { Bucket } from '@aws-cdk/aws-s3';
import { BucketDeployment, Source } from '@aws-cdk/aws-s3-deployment';
import { Construct, RemovalPolicy } from '@aws-cdk/core';
import * as path from 'path';
export interface WebsiteBucketProps {
/**
* Name of the bucket
*
* @default - Assigned by CloudFormation (recommended).
*/
readonly bucketName?: string;
/**
* Policy to apply when the bucket is removed from this stack.
*
* @default - The bucket will be orphaned.
*/
readonly removalPolicy?: RemovalPolicy;
/**
* The source from which to deploy the website
*
* @default - Dummy placeholder
*/
readonly source?: string;
/**
* Disable website deployment
*
* @default - false
*/
readonly disableUpload?: boolean;
/**
* The index page for the site like 'index.html'
*
* @default - index.html
*/
readonly websiteIndexDocument?: string;
/**
* The error page for the site like 'error.html'
*
* @default - error.html
*/
readonly websiteErrorDocument?: string;
}
export class WebsiteBucket extends Construct {
public readonly s3OriginConfig: S3OriginConfig;
constructor(scope: Construct, id: string, props: WebsiteBucketProps = {}) {
super(scope, id);
const {
bucketName,
removalPolicy = RemovalPolicy.RETAIN,
disableUpload = false,
source,
websiteIndexDocument,
websiteErrorDocument,
} = props;
const bucket = new Bucket(this, 'WebsiteBucket', {
bucketName,
removalPolicy,
websiteIndexDocument: websiteIndexDocument || 'index.html',
websiteErrorDocument: websiteErrorDocument || 'error.html',
});
const originId = new CfnCloudFrontOriginAccessIdentity(
this,
'OriginAccessIdentity',
{
cloudFrontOriginAccessIdentityConfig: {
comment: `CloudFront OriginAccessIdentity for ${bucket.bucketName}`,
},
},
);
bucket.grantRead(
new CanonicalUserPrincipal(originId.attrS3CanonicalUserId),
);
if (!disableUpload) {
const placeHolderSource = path.join(__dirname, '..', 'website');
new BucketDeployment(this, 'WebsiteDeployment', {
sources: [Source.asset(source || placeHolderSource)],
destinationBucket: bucket,
retainOnDelete: removalPolicy === RemovalPolicy.RETAIN,
});
}
this.s3OriginConfig = {
originAccessIdentityId: originId.ref,
s3BucketSource: bucket,
};
}
}