-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathminecraft-stack.ts
378 lines (345 loc) · 11.7 KB
/
minecraft-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
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import * as path from 'path';
import {
Stack,
StackProps,
aws_ec2 as ec2,
aws_efs as efs,
aws_iam as iam,
aws_ecs as ecs,
aws_logs as logs,
aws_sns as sns,
RemovalPolicy,
Arn,
ArnFormat,
} from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { constants } from './constants';
import { SSMParameterReader } from './ssm-parameter-reader';
import { StackConfig } from './types';
import { getMinecraftServerConfig, isDockerInstalled } from './util';
import { UserData } from 'aws-cdk-lib/lib/aws-ec2';
interface MinecraftStackProps extends StackProps {
config: Readonly<StackConfig>;
}
export class MinecraftStack extends Stack {
constructor(scope: Construct, id: string, props: MinecraftStackProps) {
super(scope, id, props);
const { config } = props;
const vpc = config.vpcId
? ec2.Vpc.fromLookup(this, 'Vpc', { vpcId: config.vpcId })
: new ec2.Vpc(this, 'Vpc', {
maxAzs: 3,
natGateways: 0,
});
const fileSystem = new efs.FileSystem(this, 'FileSystem', {
vpc,
removalPolicy: RemovalPolicy.SNAPSHOT,
});
const accessPoint = new efs.AccessPoint(this, 'AccessPoint', {
fileSystem,
path: '/minecraft',
posixUser: {
uid: '1000',
gid: '1000',
},
createAcl: {
ownerGid: '1000',
ownerUid: '1000',
permissions: '0755',
},
});
const efsReadWriteDataPolicy = new iam.Policy(this, 'DataRWPolicy', {
statements: [
new iam.PolicyStatement({
sid: 'AllowReadWriteOnEFS',
effect: iam.Effect.ALLOW,
actions: [
'elasticfilesystem:ClientMount',
'elasticfilesystem:ClientWrite',
'elasticfilesystem:DescribeFileSystems',
],
resources: [fileSystem.fileSystemArn],
conditions: {
StringEquals: {
'elasticfilesystem:AccessPointArn': accessPoint.accessPointArn,
},
},
}),
],
});
const ecsTaskRole = new iam.Role(this, 'TaskRole', {
assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'),
description: 'Minecraft ECS task role',
});
efsReadWriteDataPolicy.attachToRole(ecsTaskRole);
const cluster = new ecs.Cluster(this, 'Cluster', {
clusterName: constants.CLUSTER_NAME,
vpc,
containerInsights: true, // TODO: Add config for container insights
enableFargateCapacityProviders: true,
});
const taskDefinition = new ecs.FargateTaskDefinition(
this,
'TaskDefinition',
{
taskRole: ecsTaskRole,
memoryLimitMiB: config.taskMemory,
cpu: config.taskCpu,
volumes: [
{
name: constants.ECS_VOLUME_NAME,
efsVolumeConfiguration: {
fileSystemId: fileSystem.fileSystemId,
transitEncryption: 'ENABLED',
authorizationConfig: {
accessPointId: accessPoint.accessPointId,
iam: 'ENABLED',
},
},
},
],
}
);
const minecraftServerConfig = getMinecraftServerConfig(
config.minecraftEdition
);
const minecraftServerContainer = new ecs.ContainerDefinition(
this,
'ServerContainer',
{
containerName: constants.MC_SERVER_CONTAINER_NAME,
image: ecs.ContainerImage.fromRegistry(minecraftServerConfig.image),
portMappings: [
{
containerPort: minecraftServerConfig.port,
hostPort: minecraftServerConfig.port,
protocol: minecraftServerConfig.protocol,
},
],
environment: config.minecraftImageEnv,
essential: false,
taskDefinition,
logging: config.debug
? new ecs.AwsLogDriver({
logRetention: logs.RetentionDays.THREE_DAYS,
streamPrefix: constants.MC_SERVER_CONTAINER_NAME,
})
: undefined,
}
);
minecraftServerContainer.addMountPoints({
containerPath: '/data',
sourceVolume: constants.ECS_VOLUME_NAME,
readOnly: false,
});
const serviceSecurityGroup = new ec2.SecurityGroup(
this,
'ServiceSecurityGroup',
{
vpc,
description: 'Security group for Minecraft on-demand',
}
);
serviceSecurityGroup.addIngressRule(
ec2.Peer.anyIpv4(),
minecraftServerConfig.ingressRulePort
);
const minecraftServerService = new ecs.FargateService(
this,
'FargateService',
{
cluster,
capacityProviderStrategies: [
{
capacityProvider: config.useFargateSpot
? 'FARGATE_SPOT'
: 'FARGATE',
weight: 1,
base: 1,
},
],
taskDefinition: taskDefinition,
platformVersion: ecs.FargatePlatformVersion.LATEST,
serviceName: constants.SERVICE_NAME,
desiredCount: 0,
assignPublicIp: true,
securityGroups: [serviceSecurityGroup],
}
);
/* Allow access to EFS from Fargate service security group */
fileSystem.connections.allowDefaultPortFrom(
minecraftServerService.connections
);
const hostedZoneId = new SSMParameterReader(
this,
'Route53HostedZoneIdReader',
{
parameterName: constants.HOSTED_ZONE_SSM_PARAMETER,
region: constants.DOMAIN_STACK_REGION,
}
).getParameterValue();
let snsTopicArn = '';
/* Create SNS Topic if SNS_EMAIL is provided */
if (config.snsEmailAddress) {
const snsTopic = new sns.Topic(this, 'ServerSnsTopic', {
displayName: 'Minecraft Server Notifications',
});
snsTopic.grantPublish(ecsTaskRole);
const emailSubscription = new sns.Subscription(
this,
'EmailSubscription',
{
protocol: sns.SubscriptionProtocol.EMAIL,
topic: snsTopic,
endpoint: config.snsEmailAddress,
}
);
snsTopicArn = snsTopic.topicArn;
}
const watchdogContainer = new ecs.ContainerDefinition(
this,
'WatchDogContainer',
{
containerName: constants.WATCHDOG_SERVER_CONTAINER_NAME,
image: isDockerInstalled()
? ecs.ContainerImage.fromAsset(
path.resolve(__dirname, '../../minecraft-ecsfargate-watchdog/')
)
: ecs.ContainerImage.fromRegistry(
'doctorray/minecraft-ecsfargate-watchdog'
),
essential: true,
taskDefinition: taskDefinition,
environment: {
CLUSTER: constants.CLUSTER_NAME,
SERVICE: constants.SERVICE_NAME,
DNSZONE: hostedZoneId,
SERVERNAME: `${config.subdomainPart}.${config.domainName}`,
SNSTOPIC: snsTopicArn,
TWILIOFROM: config.twilio.phoneFrom,
TWILIOTO: config.twilio.phoneTo,
TWILIOAID: config.twilio.accountId,
TWILIOAUTH: config.twilio.authCode,
STARTUPMIN: config.startupMinutes,
SHUTDOWNMIN: config.shutdownMinutes,
},
logging: config.debug
? new ecs.AwsLogDriver({
logRetention: logs.RetentionDays.THREE_DAYS,
streamPrefix: constants.WATCHDOG_SERVER_CONTAINER_NAME,
})
: undefined,
}
);
const serviceControlPolicy = new iam.Policy(this, 'ServiceControlPolicy', {
statements: [
new iam.PolicyStatement({
sid: 'AllowAllOnServiceAndTask',
effect: iam.Effect.ALLOW,
actions: ['ecs:*'],
resources: [
minecraftServerService.serviceArn,
/* arn:aws:ecs:<region>:<account_number>:task/minecraft/* */
Arn.format(
{
service: 'ecs',
resource: 'task',
resourceName: `${constants.CLUSTER_NAME}/*`,
arnFormat: ArnFormat.SLASH_RESOURCE_NAME,
},
this
),
],
}),
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['ec2:DescribeNetworkInterfaces'],
resources: ['*'],
}),
],
});
serviceControlPolicy.attachToRole(ecsTaskRole);
/**
* Add service control policy to the launcher lambda from the other stack
*/
const launcherLambdaRoleArn = new SSMParameterReader(
this,
'launcherLambdaRoleArn',
{
parameterName: constants.LAUNCHER_LAMBDA_ARN_SSM_PARAMETER,
region: constants.DOMAIN_STACK_REGION,
}
).getParameterValue();
const launcherLambdaRole = iam.Role.fromRoleArn(
this,
'LauncherLambdaRole',
launcherLambdaRoleArn
);
serviceControlPolicy.attachToRole(launcherLambdaRole);
/**
* This policy gives permission to our ECS task to update the A record
* associated with our minecraft server. Retrieve the hosted zone identifier
* from Route 53 and place it in the Resource line within this policy.
*/
const iamRoute53Policy = new iam.Policy(this, 'IamRoute53Policy', {
statements: [
new iam.PolicyStatement({
sid: 'AllowEditRecordSets',
effect: iam.Effect.ALLOW,
actions: [
'route53:GetHostedZone',
'route53:ChangeResourceRecordSets',
'route53:ListResourceRecordSets',
],
resources: [`arn:aws:route53:::hostedzone/${hostedZoneId}`],
}),
],
});
iamRoute53Policy.attachToRole(ecsTaskRole);
const efsMaintenanceInstanceRole = new iam.Role(this, 'EFSMaintenanceRole', {
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
description: 'Minecraft EC2 instance role',
});
efsReadWriteDataPolicy.attachToRole(efsMaintenanceInstanceRole);
const efsMaintenanceSecurityGroup = new ec2.SecurityGroup(
this,
'EfsMaintenanceSecurityGroup',
{
vpc,
description: 'Security group for Minecraft on-demand EFS Maintenance Instances',
}
);
efsMaintenanceSecurityGroup.addIngressRule(
ec2.Peer.anyIpv4(),
ec2.Port.tcp(22)
);
/* Allow access to EFS from Fargate service security group */
fileSystem.connections.allowDefaultPortFrom(
efsMaintenanceSecurityGroup
);
const efsMaintenanceLaunchTemplate = new ec2.LaunchTemplate(this, 'EFSMaintenanceLaunchTemplate', {
userData: UserData.custom(`#cloud-config
package_update: true
package_upgrade: true
runcmd:
- yum install -y amazon-efs-utils
- apt-get -y install amazon-efs-utils
- yum install -y nfs-utils
- apt-get -y install nfs-common
- file_system_id_1=${fileSystem.fileSystemId}
- efs_mount_point_1=/mnt/efs/fs1
- mkdir -p "\${efs_mount_point_1}"
- test -f "/sbin/mount.efs" && printf "\\n\${file_system_id_1}:/ \${efs_mount_point_1} efs iam,tls,_netdev\\n" >> /etc/fstab || printf "\\n\${file_system_id_1}.efs.${config.serverRegion}.amazonaws.com:/ \${efs_mount_point_1} nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport,_netdev 0 0\\n" >> /etc/fstab
- test -f "/sbin/mount.efs" && grep -ozP 'client-info]\\nsource' '/etc/amazon/efs/efs-utils.conf'; if [[ $? == 1 ]]; then printf "\\n[client-info]\\nsource=liw\\n" >> /etc/amazon/efs/efs-utils.conf; fi;
- retryCnt=15; waitTime=30; while true; do mount -a -t efs,nfs4 defaults; if [ $? = 0 ] || [ $retryCnt -lt 1 ]; then echo File system mounted successfully; break; fi; echo File system not available, retrying to mount.; ((retryCnt--)); sleep $waitTime; done;
`),
role: efsMaintenanceInstanceRole,
spotOptions: {
interruptionBehavior: ec2.SpotInstanceInterruption.TERMINATE,
requestType: ec2.SpotRequestType.ONE_TIME
},
securityGroup: efsMaintenanceSecurityGroup,
instanceInitiatedShutdownBehavior: ec2.InstanceInitiatedShutdownBehavior.TERMINATE
});
}
}