/
static-stack.ts
83 lines (77 loc) · 2.39 KB
/
static-stack.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
import * as cdk from "@aws-cdk/core";
import * as s3 from "@aws-cdk/aws-s3";
import * as cloudfront from "@aws-cdk/aws-cloudfront";
import * as iam from "@aws-cdk/aws-iam";
import * as elb from "@aws-cdk/aws-elasticloadbalancingv2";
import { Duration } from "@aws-cdk/core";
interface StaticStackProps {
nextServerAlb: elb.IApplicationLoadBalancer;
}
export class StaticStack extends cdk.Stack {
public readonly staticBucket: s3.Bucket;
constructor(
scope: cdk.Construct,
id: string,
props: cdk.StackProps & StaticStackProps
) {
super(scope, id, props);
this.staticBucket = new s3.Bucket(this, "nextjs-on-ecs-static-bucket", {
bucketName: "nextjs-on-ecs-static-bucket",
versioned: false,
removalPolicy: cdk.RemovalPolicy.DESTROY
});
// CloudFront で設定する オリジンアクセスアイデンティティ を作成する
const oai = new cloudfront.OriginAccessIdentity(
this,
"nextjs-on-ecs-cloudfront-oai",
{
comment: "s3 access."
}
);
// CloudFront -> staticBucketへのアクセス許可
this.staticBucket.grantRead(oai);
const distribution = new cloudfront.CloudFrontWebDistribution(
this,
"nextjs-on-ecs-cloudfront",
{
defaultRootObject: "",
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.ALLOW_ALL,
originConfigs: [
{
s3OriginSource: {
s3BucketSource: this.staticBucket,
originAccessIdentity: oai
},
behaviors: [
{
pathPattern: "/_next/static/*",
compress: true
}
]
},
{
customOriginSource: {
domainName: props.nextServerAlb.loadBalancerDnsName,
originProtocolPolicy: cloudfront.OriginProtocolPolicy.HTTP_ONLY
},
behaviors: [
{
isDefaultBehavior: true,
allowedMethods: cloudfront.CloudFrontAllowedMethods.ALL,
forwardedValues: {
queryString: true,
cookies: {
forward: "all"
}
},
maxTtl: Duration.seconds(0),
minTtl: Duration.seconds(0),
defaultTtl: Duration.seconds(0)
}
]
}
]
}
);
}
}