-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.yaml
421 lines (377 loc) · 12.1 KB
/
template.yaml
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31
Description: Valheim
Parameters:
Image:
Type: String
Default: lloesche/valheim-server
Name:
Type: String
Default: earth
StatusPort:
Type: Number
Default: 80
Resources:
############################
# Misc
############################
Secret:
Type: AWS::SecretsManager::Secret
Properties:
Name: !Sub ${ AWS::StackName }
GenerateSecretString:
SecretStringTemplate: '{}'
GenerateStringKey: password
PasswordLength: 30
ExcludePunctuation: true
Bucket:
Type: AWS::S3::Bucket
Properties:
VersioningConfiguration:
Status: Enabled
LifecycleConfiguration:
Rules:
- Status: Enabled
NoncurrentVersionExpirationInDays: 10
############################
# Network
############################
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.0.0.0/16
EnableDnsHostnames: true
Subnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
CidrBlock: 10.0.0.0/24
AvailabilityZone: !Sub ${ AWS::Region }a
MapPublicIpOnLaunch: true
# Allow outbound internet access
# This is required for various reasons - including:
# - access to secrets manager
# - access to download/update game files
InternetGateway:
Type: AWS::EC2::InternetGateway
AttachGateway:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref VPC
InternetGatewayId: !Ref InternetGateway
RouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
InternetRoute:
Type: AWS::EC2::Route
DependsOn: InternetGateway
Properties:
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
RouteTableId: !Ref RouteTable
SubnetRouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref RouteTable
SubnetId: !Ref Subnet
############################
# Hosting
############################
Cluster:
Type: AWS::ECS::Cluster
Properties:
ClusterName: !Sub ${ AWS::StackName }
CapacityProviders:
- FARGATE_SPOT
DefaultCapacityProviderStrategy:
- CapacityProvider: FARGATE_SPOT
Weight: 1
ExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: ecs-tasks.amazonaws.com
Action: 'sts:AssumeRole'
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
Policies:
- PolicyName: secrets
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- secretsmanager:GetSecretValue
- secretsmanager:DescribeSecret
Resource: !Ref Secret
TaskRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: ecs-tasks.amazonaws.com
Action: 'sts:AssumeRole'
Policies:
- PolicyName: backups
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- s3:DeleteObject
- s3:GetBucketLocation
- s3:GetObject
- s3:ListBucket
- s3:PutObject
Resource:
- !Sub arn:${ AWS::Partition }:s3:::${ Bucket }
- !Sub arn:${ AWS::Partition }:s3:::${ Bucket }/*
LogGroup:
Type: AWS::Logs::LogGroup
Properties:
RetentionInDays: 3
TaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
Family: !Sub ${ AWS::StackName }
NetworkMode: awsvpc
RequiresCompatibilities:
- FARGATE
Cpu: 2048
Memory: 4GB
ExecutionRoleArn: !GetAtt ExecutionRole.Arn
TaskRoleArn: !GetAtt TaskRole.Arn
ContainerDefinitions:
- Name: !Sub ${ AWS::StackName }
Image: !Ref Image
PortMappings:
- ContainerPort: !Ref StatusPort
Protocol: tcp
- ContainerPort: 2456
Protocol: udp
- ContainerPort: 2457
Protocol: udp
- ContainerPort: 2458
Protocol: udp
Environment:
- Name: SERVER_NAME
Value: !Ref Name
- Name: SERVER_PORT
Value: 2456
- Name: WORLD_NAME
Value: !Ref Name
- Name: SERVER_PUBLIC
Value: 'true'
- Name: UPDATE_INTERVAL
Value: '900'
- Name: BACKUPS_INTERVAL
Value: '3600'
- Name: BACKUPS_DIRECTORY
Value: '/config/backups'
- Name: BACKUPS_MAX_AGE
Value: '3'
- Name: BACKUPS_DIRECTORY_PERMISSIONS
Value: '755'
- Name: BACKUPS_FILE_PERMISSIONS
Value: '644'
- Name: CONFIG_DIRECTORY_PERMISSIONS
Value: '755'
- Name: WORLDS_DIRECTORY_PERMISSIONS
Value: '755'
- Name: WORLDS_FILE_PERMISSIONS
Value: '644'
- Name: DNS_1
Value: '10.0.0.2'
- Name: DNS_2
Value: '10.0.0.2'
- Name: STEAMCMD_ARGS
Value: 'validate'
- Name: STATUS_HTTP_PORT
Value: !Ref StatusPort
## HOOKS
# on cold-start: install pre-reqs
- Name: POST_BOOTSTRAP_HOOK
Value:
Fn::Join:
- ' && '
-
# install awscli
- curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
- unzip awscliv2.zip
- ./aws/install
- aws --version
# on startup: re-hydrate world
- Name: PRE_SERVER_RUN_HOOK
Value: !Sub aws s3 sync s3://${ Bucket }/worlds /config/worlds --delete
# on shutdown: de-hydrate world
- Name: POST_SERVER_SHUTDOWN_HOOK
Value: !Sub aws s3 sync /config/worlds s3://${ Bucket }/worlds --delete
# on backup: sync to s3
- Name: POST_BACKUP_HOOK
Value: !Sub aws s3 sync /config/backups s3://${ Bucket }/backups --delete
Secrets:
- Name: SERVER_PASS
ValueFrom: !Sub "${ Secret }:password::"
LogConfiguration:
LogDriver: awslogs
Options:
awslogs-region: !Ref AWS::Region
awslogs-group: !Ref LogGroup
awslogs-stream-prefix: ecs
SecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
VpcId: !Ref VPC
GroupDescription: pwmcintyre
SecurityGroupIngress:
- IpProtocol: udp
FromPort: 2456
ToPort: 2458
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: !Ref StatusPort
ToPort: !Ref StatusPort
CidrIp: 0.0.0.0/0
Service:
Type: AWS::ECS::Service
Properties:
ServiceName: !Sub ${ AWS::StackName }
Cluster: !Ref Cluster
TaskDefinition: !Ref TaskDefinition
DesiredCount: 0
LaunchType: FARGATE
EnableExecuteCommand: 'true'
NetworkConfiguration:
AwsvpcConfiguration:
AssignPublicIp: ENABLED
SecurityGroups:
- !GetAtt SecurityGroup.GroupId
Subnets:
- !Ref Subnet
############################
# Functions
############################
StartFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: !Sub ${ AWS::StackName }-start
Runtime: nodejs12.x
Handler: index.handler
MemorySize: 128
Timeout: 300
Environment:
Variables:
CLUSTER: !GetAtt Service.Name
SERVICE: !Ref Cluster
SECRET: !Sub ${ AWS::StackName }
BUCKET: !Ref Bucket
Policies:
- Version: '2012-10-17'
Statement:
- Effect: Allow
Action: ec2:DescribeNetworkInterfaces
Resource: '*'
- Effect: Allow
Action: secretsmanager:GetSecretValue
Resource: !Ref Secret
- Effect: Allow
Action:
- ecs:UpdateService
- ecs:DescribeServices
- ecs:ListTasks
- ecs:DescribeTasks
Resource: '*'
Condition:
StringEquals:
'ecs:cluster': !GetAtt Cluster.Arn
InlineCode: |
const AWS = require('aws-sdk')
const ecs = new AWS.ECS()
const secrets = new AWS.SecretsManager()
const ec2 = new AWS.EC2()
function log(message, context) {
console.log(JSON.stringify({ message, ...context }))
}
// up handler
exports.handler = async () => {
// get env vars
const cluster = process.env.CLUSTER
const service = process.env.SERVICE
const SecretId = process.env.SECRET
const bucket = process.env.BUCKET
// start
await ecs.updateService({ cluster, service, desiredCount: 1 }).promise()
log("started", { cluster, service })
// wait until stable
await ecs.waitFor("servicesStable", { cluster, services: [service] }).promise()
log("service stable", { cluster, service })
// get task
const task = await ecs.listTasks({ cluster, serviceName: service }).promise()
.then( res => res.taskArns[0] )
// wait until task stable / get ENI
const eni = await ecs.waitFor("tasksRunning", { cluster, tasks: [task] }).promise()
.then( res => res.tasks[0].attachments[0].details.filter( a => a.name == "networkInterfaceId" )[0].value )
log("task stable", { cluster, service, task })
// get PublicIP
const ip = await ec2.describeNetworkInterfaces({ NetworkInterfaceIds: [eni] }).promise()
.then( res => res.NetworkInterfaces[0].Association.PublicIp )
// get password
const password = await secrets.getSecretValue({ SecretId }).promise()
.then( res => {
const value = res.SecretString
const blob = JSON.parse( value )
return blob["password"]
})
// respond
return { message: "started", ip, password, bucket }
}
StopFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: !Sub ${ AWS::StackName }-stop
Runtime: nodejs12.x
Handler: index.handler
MemorySize: 128
Timeout: 300
Environment:
Variables:
CLUSTER: !GetAtt Service.Name
SERVICE: !Ref Cluster
BUCKET: !Ref Bucket
Policies:
- Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ecs:UpdateService
- ecs:DescribeServices
Resource: '*'
Condition:
StringEquals:
'ecs:cluster': !GetAtt Cluster.Arn
InlineCode: |
const AWS = require('aws-sdk')
const ecs = new AWS.ECS()
function log(message, context) {
console.log(JSON.stringify({ message, ...context }))
}
// up handler
exports.handler = async () => {
// get env vars
const cluster = process.env.CLUSTER
const service = process.env.SERVICE
// stop
await ecs.updateService({ cluster, service, desiredCount: 0 }).promise()
log("stopping", { cluster, service })
// wait until inactive
await ecs.waitFor("servicesInactive", { cluster, services: [service] }).promise()
log("service inactive", { cluster, service })
// respond
return { message: "stopped", bucket }
}