/
service.ts
281 lines (261 loc) · 10.2 KB
/
service.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
import * as cdk from "aws-cdk-lib";
import { Construct } from "constructs";
import { readFileSync } from "fs";
export interface ServiceProps {
serviceName: string;
area: "tokyo" | "osaka";
azPrimary: string;
azSecondary: string;
userDataFilePath: string;
globalDatabaseIdentifier: string;
isPrimaryDatabaseCluster: boolean;
hostedZoneName: string;
globalDomainName: string;
vpc: cdk.aws_ec2.IVpc;
publicSubnets: cdk.aws_ec2.SubnetSelection;
privateSubnets: cdk.aws_ec2.SubnetSelection;
isolatedSubnets: cdk.aws_ec2.SubnetSelection;
dbCluster: cdk.aws_rds.DatabaseCluster;
dbListenerPort: number;
}
export class Service extends Construct {
readonly hostedZone: cdk.aws_route53.IHostedZone;
readonly nlb: cdk.aws_elasticloadbalancingv2.INetworkLoadBalancer;
constructor(scope: Construct, id: string, props: ServiceProps) {
super(scope, id);
// Hosted zone
this.hostedZone = cdk.aws_route53.HostedZone.fromLookup(this, "HostedZone", {
domainName: props.hostedZoneName,
});
// Certificate
const certificate = new cdk.aws_certificatemanager.Certificate(this, "Certificate", {
certificateName: `${props.serviceName}-${props.area}-certificate`,
domainName: props.globalDomainName,
subjectAlternativeNames: [props.globalDomainName, "*." + props.globalDomainName],
validation: cdk.aws_certificatemanager.CertificateValidation.fromDns(this.hostedZone),
});
// EC2 instance role (currently not in use)
const ec2Role = new cdk.aws_iam.Role(this, "InstanceRole", {
roleName: `${props.serviceName}-${props.area}-instance-role`,
assumedBy: new cdk.aws_iam.ServicePrincipal("ec2.amazonaws.com"),
managedPolicies: [
cdk.aws_iam.ManagedPolicy.fromManagedPolicyArn(
this,
"SSMAccess",
"arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
),
],
});
new cdk.aws_iam.CfnInstanceProfile(this, "InstanceProfile", {
instanceProfileName: `${props.serviceName}-${props.area}-instance-profile`,
roles: [ec2Role.roleName],
});
// EC2 SecurityGroup
const ec2SecurityGroupName = `${props.serviceName}-${props.area}-ec2-security-group`;
const ec2SecurityGroup = new cdk.aws_ec2.SecurityGroup(this, "InstanceSecurityGroup", {
securityGroupName: ec2SecurityGroupName,
description: ec2SecurityGroupName,
vpc: props.vpc,
allowAllOutbound: true,
});
cdk.Tags.of(ec2SecurityGroup).add("Name", ec2SecurityGroupName);
// EC2 UserData
const userData = cdk.aws_ec2.UserData.forLinux({ shebang: "#!/bin/bash" });
userData.addCommands(readFileSync(props.userDataFilePath, "utf8"));
// EC2 LaunchTemplate
const launchTemplate = new cdk.aws_ec2.LaunchTemplate(this, "LaunchTemplate", {
launchTemplateName: `${props.serviceName}-${props.area}-template`,
instanceType: cdk.aws_ec2.InstanceType.of(cdk.aws_ec2.InstanceClass.T3, cdk.aws_ec2.InstanceSize.MICRO),
cpuCredits: cdk.aws_ec2.CpuCredits.STANDARD,
machineImage: cdk.aws_ec2.MachineImage.latestAmazonLinux2({
cpuType: cdk.aws_ec2.AmazonLinuxCpuType.X86_64,
}),
blockDevices: [
{
deviceName: "/dev/xvda",
volume: cdk.aws_ec2.BlockDeviceVolume.ebs(8, {
volumeType: cdk.aws_ec2.EbsDeviceVolumeType.GP3,
}),
},
],
securityGroup: ec2SecurityGroup,
role: ec2Role,
requireImdsv2: true,
userData: userData,
});
// AutoScalingGroup
const asg = new cdk.aws_autoscaling.AutoScalingGroup(this, "AutoScalingGroup", {
autoScalingGroupName: `${props.serviceName}-${props.area}-instance`,
launchTemplate: launchTemplate,
minCapacity: 2,
maxCapacity: 2,
vpc: props.vpc,
vpcSubnets: props.privateSubnets,
healthCheck: cdk.aws_autoscaling.HealthCheck.elb({
grace: cdk.Duration.minutes(10),
}),
});
props.dbCluster.connections.allowDefaultPortFrom(
asg,
`Allow access to database from EC2 instances on port ${props.dbListenerPort}`
);
// ALB security group
const albSecurityGroupName = `${props.serviceName}-${props.area}-alb-security-group`;
const albSecurityGroup = new cdk.aws_ec2.SecurityGroup(this, "ALBSecurityGroup", {
securityGroupName: albSecurityGroupName,
description: albSecurityGroupName,
vpc: props.vpc,
allowAllOutbound: false,
});
cdk.Tags.of(albSecurityGroup).add("Name", albSecurityGroupName);
// ALB
const alb = new cdk.aws_elasticloadbalancingv2.ApplicationLoadBalancer(this, "ALB", {
loadBalancerName: `${props.serviceName}-${props.area}-alb`,
vpc: props.vpc,
vpcSubnets: props.privateSubnets,
internetFacing: false,
securityGroup: albSecurityGroup,
});
alb.node.addDependency(asg);
albSecurityGroup.addIngressRule(
cdk.aws_ec2.Peer.ipv4("0.0.0.0/0"),
cdk.aws_ec2.Port.tcp(443),
"Allow access to ALB from anyone on port 443",
false
);
albSecurityGroup.addIngressRule(
cdk.aws_ec2.Peer.ipv4("0.0.0.0/0"),
cdk.aws_ec2.Port.tcp(80),
"Allow access to ALB from anyone on port 80",
false
);
asg.connections.allowFrom(alb, cdk.aws_ec2.Port.tcp(80), "Allow access to EC2 instance from ALB on port 80");
// ALB HTTPS listener
alb.addListener("ListenerHTTPS", {
protocol: cdk.aws_elasticloadbalancingv2.ApplicationProtocol.HTTPS,
sslPolicy: cdk.aws_elasticloadbalancingv2.SslPolicy.TLS13_13,
certificates: [
{
certificateArn: certificate.certificateArn,
},
],
defaultTargetGroups: [
new cdk.aws_elasticloadbalancingv2.ApplicationTargetGroup(this, "ALBTargetGroup", {
targetGroupName: `${props.serviceName}-${props.area}-alb-tg`,
targetType: cdk.aws_elasticloadbalancingv2.TargetType.INSTANCE,
targets: [asg],
protocol: cdk.aws_elasticloadbalancingv2.ApplicationProtocol.HTTP,
port: 80,
healthCheck: {
protocol: cdk.aws_elasticloadbalancingv2.Protocol.HTTP,
port: "traffic-port",
},
vpc: props.vpc,
}),
],
});
// ALB HTTP listener
alb.addListener("ListenerHTTP", {
protocol: cdk.aws_elasticloadbalancingv2.ApplicationProtocol.HTTP,
defaultAction: cdk.aws_elasticloadbalancingv2.ListenerAction.redirect({
protocol: "HTTPS",
port: "443",
host: "#{host}",
path: "/#{path}",
query: "#{query}",
permanent: true,
}),
});
// EC2 Instance Connect endpoint SecurityGroup
const eicSecurityGroupName = `${props.serviceName}-${props.area}-eic-security-group`;
const eicSecurityGroup = new cdk.aws_ec2.SecurityGroup(this, "InstanceConnectSecurityGroup", {
securityGroupName: eicSecurityGroupName,
description: eicSecurityGroupName,
vpc: props.vpc,
allowAllOutbound: false,
});
cdk.Tags.of(eicSecurityGroup).add("Name", eicSecurityGroupName);
eicSecurityGroup.connections.allowTo(
asg,
cdk.aws_ec2.Port.tcp(22),
"Allow access to EC2 instance from EC2 Instance Connect on port 22"
);
// EC2 Instance Connect endpoint
new cdk.aws_ec2.CfnInstanceConnectEndpoint(this, "InstanceConnectEndpoint", {
subnetId: props.vpc.publicSubnets[0].subnetId,
securityGroupIds: [eicSecurityGroup.securityGroupId],
preserveClientIp: true,
clientToken: `${props.serviceName}-${props.area}-eic-client-token`,
});
ec2SecurityGroup.addIngressRule(
cdk.aws_ec2.Peer.securityGroupId(eicSecurityGroup.securityGroupId),
cdk.aws_ec2.Port.tcp(22),
"Allow access to EC2 instance from EC2 Instance Connect on port 22",
false
);
// NLB
this.nlb = new cdk.aws_elasticloadbalancingv2.NetworkLoadBalancer(this, "NLB", {
loadBalancerName: `${props.serviceName}-${props.area}-nlb`,
vpc: props.vpc,
vpcSubnets: props.publicSubnets,
internetFacing: true,
crossZoneEnabled: true,
});
this.nlb.node.addDependency(alb);
// Allocate EIPs for NLB
const cfnLoadBalancer = this.nlb.node.defaultChild as cdk.aws_elasticloadbalancingv2.CfnLoadBalancer;
cfnLoadBalancer.subnetMappings = props.vpc.publicSubnets.map((subnet, i) => {
const eip = new cdk.aws_ec2.CfnEIP(this, `EIP${i}`, {
domain: "vpc",
});
this.nlb.node.addDependency(eip);
return {
subnetId: subnet.subnetId,
allocationId: cdk.Token.asString(eip.getAtt("AllocationId")),
} as cdk.aws_elasticloadbalancingv2.CfnLoadBalancer.SubnetMappingProperty;
});
if (cfnLoadBalancer.subnetMappings !== undefined) {
cfnLoadBalancer.subnets = undefined;
}
// NLB TCP443 listerner
this.nlb.addListener("ListenerTCP443", {
protocol: cdk.aws_elasticloadbalancingv2.Protocol.TCP,
port: 443,
defaultTargetGroups: [
new cdk.aws_elasticloadbalancingv2.NetworkTargetGroup(this, "NLBTargetGroupTCP443", {
targetGroupName: `${props.serviceName}-${props.area}-nlb-tg-443`,
targetType: cdk.aws_elasticloadbalancingv2.TargetType.ALB,
targets: [new cdk.aws_elasticloadbalancingv2_targets.AlbTarget(alb, 443)],
protocol: cdk.aws_elasticloadbalancingv2.Protocol.TCP,
port: 443,
preserveClientIp: true,
healthCheck: {
protocol: cdk.aws_elasticloadbalancingv2.Protocol.HTTP,
port: "80",
},
vpc: props.vpc,
}),
],
});
// NLB TCP80 listerner
this.nlb.addListener("ListenerTCP80", {
protocol: cdk.aws_elasticloadbalancingv2.Protocol.TCP,
port: 80,
defaultTargetGroups: [
new cdk.aws_elasticloadbalancingv2.NetworkTargetGroup(this, "NLBTargetGroupTCP80", {
targetGroupName: `${props.serviceName}-${props.area}-nlb-tg-80`,
targetType: cdk.aws_elasticloadbalancingv2.TargetType.ALB,
targets: [new cdk.aws_elasticloadbalancingv2_targets.AlbTarget(alb, 80)],
protocol: cdk.aws_elasticloadbalancingv2.Protocol.TCP,
port: 80,
preserveClientIp: true,
healthCheck: {
protocol: cdk.aws_elasticloadbalancingv2.Protocol.HTTP,
port: "traffic-port",
},
vpc: props.vpc,
}),
],
});
}
}