/
ecs-base.template
592 lines (576 loc) · 19.6 KB
/
ecs-base.template
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
AWSTemplateFormatVersion: 2010-09-09
Description: AutoScaling ECS Cluster
Metadata:
DefaultName: EcsClusterBase
Dependencies:
- TemplatePath: networking/vpc
Resources:
ElbTargetSg: ElbTargetSecGroup
Outputs:
AzCount: AzCount
- TemplatePath: networking/elb-subnets
Parameters:
VpcId: VpcId
Outputs:
ServerSubnets: WebServerSubnets
NestedDependency: networking/vpc
- TemplatePath: analytics/logs-store
Resources:
DiagnosticsMp: LinuxLogPolicy
Parameters:
ClusterMinimumHosts:
Description: 'Minimum number of ec2 hosts to run in the auto scaling group'
Default: 2
Type: String
ClusterMaximumHosts:
Description: 'Maximum number of ec2 hosts to run in the auto scaling group'
Default: 100
Type: String
WaitTimeout:
Description: Timeout (seconds) for the ASG's wait condition. Default 1hr.
Type: String
Default: "3600"
WaitConditionInstanceCount:
Description: 'Used to delay the cloudformation cleanup. Leave blank to disable.'
Type: String
Default: ''
KeyPairName:
Type: String
Description: Name of an existing EC2 KeyPair to enable SSH access to the ECS instances.
Default: ''
VpcId:
Description: 'VPCid associated with the subnets. [elb-subnets.parameters.VpcId]'
Type: 'AWS::EC2::VPC::Id'
AzCount:
Description: >-
Number of AZ. Third subnet will only be created if number is 3
Type: String
ServerSubnets:
Description: 'VPCid associated with the subnets.'
Type: 'List<AWS::EC2::Subnet::Id>'
ElbTargetSg:
Description: 'Elb Target Security Group.'
Type: String
InstanceType:
Description: Phabricator server instance type
Type: String
Default: t3.medium
AllowedValues:
- t3.micro
- t3.small
- t3.medium
- t3.large
- m5.large
- m5.xlarge
- m5.2xlarge
- m5.4xlarge
- m5.8xlarge
- m5.16xlarge
- r5.large
- r5.xlarge
- r5.2xlarge
- r5.4xlarge
- r5.8xlarge
- r5.16xlarge
- c5.large
- c5.xlarge
- c5.2xlarge
- c5.4xlarge
- c5.8xlarge
ConstraintDescription: Must be a valid EC2 instance type.
BcUbuntuBaseAmiId:
Description: Image id of the frontend
Type: 'AWS::EC2::Image::Id'
WindowsContainerAmiId:
Description: ECS Optimised AMI.
Type: 'AWS::EC2::Image::Id'
DiagnosticsMp:
Description: ''
Type: String
DiskSize:
Description: ''
Type: String
Default: '100'
LambdaBucket:
Description: 'Bucket where Lambda Code are Hosted.'
Type: String
Default: ''
LambdaRootPath:
Description: 'Root Path to Where Lambda Code are Hosted.'
Type: String
Default: citrus-rind/prod/
EcsAgentImage:
Description: 'AWS ECS Agent Name'
Type: String
Default: amazon/amazon-ecs-agent
EcsAgentVersion:
Description: 'AWS ECS Agent Name'
Type: String
Default: v1.28.0
EcsCpuReservationTrackingTarget:
Description: Target CPU % to target for autoscaling
Default: 60
Type: Number
PlatformType:
Description: Ec2 host type
Type: String
Default: Linux
AllowedValues:
- Linux
- Windows
ContainerAwsUtil:
Description: Container image for awscli and cfn-signal
Type: String
Default: 'bitclouded/aws-util:2-1'
Conditions:
DelayCleanUp: !Not [ !Equals [ !Ref WaitConditionInstanceCount, "" ]]
CreateWindowsResources: !Equals [ !Ref PlatformType, Windows ]
CreateLinuxResources: !Equals [ !Ref PlatformType, Linux ]
IsThreeAz: !Equals
- !Ref AzCount
- '3'
HasNoKeypair: !Equals
- !Ref KeyPairName
- ''
IsLambdaBucketParamEmpty: !Equals
- !Ref LambdaBucket
- ''
Resources:
SharedDiskGp:
Type: 'AWS::EFS::FileSystem'
Properties:
FileSystemTags:
- Key: Name
Value: !Ref 'AWS::StackName'
MountTarget1:
Type: 'AWS::EFS::MountTarget'
Properties:
FileSystemId: !Ref SharedDiskGp
SubnetId: !Select
- '0'
- !Ref ServerSubnets
SecurityGroups:
- !Ref DatabaseSg
MountTarget2:
Type: 'AWS::EFS::MountTarget'
Properties:
FileSystemId: !Ref SharedDiskGp
SubnetId: !Select ['1', !Ref ServerSubnets]
SecurityGroups:
- !Ref DatabaseSg
MountTarget3:
Type: 'AWS::EFS::MountTarget'
Condition: IsThreeAz
Properties:
FileSystemId: !Ref SharedDiskGp
SubnetId: !Select
- '2'
- !Ref ServerSubnets
SecurityGroups:
- !Ref DatabaseSg
EcsCluster:
Type: 'AWS::ECS::Cluster'
ClusterAutoScalingGroup:
Type: 'AWS::AutoScaling::AutoScalingGroup'
Properties:
VPCZoneIdentifier: !Ref ServerSubnets
LaunchTemplate:
LaunchTemplateId: !Ref ClusterLaunchTemplate
Version: !GetAtt ClusterLaunchTemplate.LatestVersionNumber
MinSize: !Ref ClusterMinimumHosts
MaxSize: !Ref ClusterMaximumHosts
Tags:
- Key: Name
Value: !Sub '${AWS::StackName} ${PlatformType} Agent'
PropagateAtLaunch: 'true'
WaitHandle:
Type: AWS::CloudFormation::WaitConditionHandle
WaitCondition:
Condition: DelayCleanUp
Type: AWS::CloudFormation::WaitCondition
DependsOn: "ClusterAutoScalingGroup"
Properties:
Handle:
Ref: "WaitHandle"
Timeout: !Ref WaitTimeout
Count: !Ref WaitConditionInstanceCount
ClusterLaunchTemplate:
Type: "AWS::EC2::LaunchTemplate"
Properties:
LaunchTemplateData:
InstanceType: !Ref InstanceType
IamInstanceProfile:
Arn: !GetAtt Ec2InstanceProfile.Arn
SecurityGroupIds:
- !Ref ElbTargetSg
- !Ref DbTargetClusterSg
KeyName: !If
- HasNoKeypair
- !Ref 'AWS::NoValue'
- !Ref KeyPairName
ImageId: !If
- CreateLinuxResources
- !Ref BcUbuntuBaseAmiId
- !Ref WindowsContainerAmiId
Monitoring:
Enabled: true
BlockDeviceMappings:
- DeviceName: /dev/sda1
Ebs:
VolumeSize: !Ref DiskSize
VolumeType: gp2
UserData: !If
- CreateLinuxResources
- !Base64
'Fn::Sub': |
#!/bin/bash
apt-get update -qqy && apt-get install -qqy nfs-common
EC2_AVAIL_ZONE=`curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone`
DIR_SRC=$EC2_AVAIL_ZONE.${SharedDiskGp}.efs.${AWS::Region}.amazonaws.com
mkdir /mnt/efs
echo -e "$DIR_SRC:/ /mnt/efs nfs defaults 0 0" | tee -a /etc/fstab
mount -a
# restart docker service so efs mount can come into effect.
service docker restart
sh -c "echo 'net.ipv4.conf.all.route_localnet = 1' >> /etc/sysctl.conf"
sysctl -p /etc/sysctl.conf
iptables -t nat -A PREROUTING -p tcp -d 169.254.170.2 --dport 80 -j DNAT --to-destination 127.0.0.1:51679
iptables -t nat -A OUTPUT -d 169.254.170.2 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 51679
docker run -d --restart=always \
--init \
-v /var/run:/var/run \
-v /var/log/ecs/:/log:Z \
-v /var/lib/ecs/data:/data:Z \
-v /etc/ecs:/etc/ecs \
-v /sbin:/sbin \
-v /lib:/lib \
-v /lib64:/lib64 \
-v /usr/lib:/usr/lib \
-v /usr/lib64:/usr/lib64 \
-v /proc:/host/proc \
-v /sys/fs/cgroup:/sys/fs/cgroup \
-v /var/run/docker.sock:/var/run/docker.sock \
--net=host \
--cap-add=sys_admin \
--cap-add=net_admin \
-e ECS_CLUSTER=${EcsCluster} \
-e ECS_ENABLE_TASK_ENI=true \
-e ECS_UPDATES_ENABLED=false \
-e ECS_ENGINE_TASK_CLEANUP_WAIT_DURATION=1h \
-e ECS_DATADIR=/data \
-e ECS_ENABLE_TASK_IAM_ROLE=true \
-e ECS_ENABLE_TASK_IAM_ROLE_NETWORK_HOST=true \
-e ECS_LOGFILE=/log/ecs-agent.log \
-e ECS_AVAILABLE_LOGGING_DRIVERS='["json-file","awslogs","none"]' \
-e ECS_LOGLEVEL=info \
-e ECS_ENABLE_CONTAINER_METADATA=true \
${EcsAgentImage}:${EcsAgentVersion}
sudo chmod a+rwx /var/run/docker.sock
docker run -t --rm ${ContainerAwsUtil} cfn-signal -e $? --region ${AWS::Region} "${WaitHandle}"
#otherwise windows
- !Base64
'Fn::Sub': |
<powershell>
[Environment]::SetEnvironmentVariable("ECS_CLUSTER", "${EcsCluster}", "Machine")
[Environment]::SetEnvironmentVariable("ECS_ENABLE_TASK_IAM_ROLE", "true", "Machine")
$gateway = (Get-WMIObject -Class Win32_IP4RouteTable | ? {
$_.Destination -eq '0.0.0.0' -and $_.Mask -eq '0.0.0.0' } |
Sort-Object Metric1 |
Select NextHop).NextHop
$ifIndex = (Get-NetAdapter -InterfaceDescription "Hyper-V Virtual Ethernet*" | Sort-Object | Select ifIndex).ifIndex
New-NetRoute -DestinationPrefix 169.254.170.2/32 -InterfaceIndex $ifIndex -NextHop $gateway
$agentZipUri = "https://s3.amazonaws.com/amazon-ecs-agent/ecs-agent-windows-${EcsAgentVersion}.zip";
$ecsExeDir = "$env:ProgramFiles\Amazon\ECS";
$zipFile = "$env:TEMP\ecs-agent.zip";
Invoke-RestMethod -OutFile $zipFile -Uri $agentZipUri;
Expand-Archive -Path $zipFile -DestinationPath $ecsExeDir -Force;
$jobname = "ECS-Agent-Init";
$script = "cd '$ecsExeDir'; .\amazon-ecs-agent.ps1";
$repeat = (New-TimeSpan -Minutes 1);
try {Unregister-ScheduledJob -Name $jobname | out-null} catch{};
Invoke-Expression("cd $ecsExeDir; .\amazon-ecs-agent.ps1");
$scriptblock = [scriptblock]::Create("$script");
$trigger = New-JobTrigger -At (Get-Date).Date -RepeatIndefinitely -RepetitionInterval $repeat -Once;
$options = New-ScheduledJobOption -RunElevated -ContinueIfGoingOnBattery -StartIfOnBattery;
Register-ScheduledJob -Name $jobname -ScriptBlock $scriptblock -Trigger $trigger -ScheduledJobOption $options -RunNow;
# end of script
# signal the cfn wait condition that this instance is up- note success (0) hard coded
cfn-signal.exe -e 0 "${WaitHandle}"
</powershell>
<persist>true</persist>
Ec2Role:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /platforms/ecs/
Policies:
- PolicyName: ecs-service
PolicyDocument:
Statement:
- Effect: Allow
Action:
- 'ecs:CreateCluster'
- 'ecs:DeregisterContainerInstance'
- 'ecs:DiscoverPollEndpoint'
- 'ecs:Poll'
- 'ecs:RegisterContainerInstance'
- 'ecs:StartTelemetrySession'
- 'ecs:Submit*'
Resource: '*'
- Effect: Allow
Action:
- 'ecr:BatchCheckLayerAvailability'
- 'ecr:BatchGetImage'
- 'ecr:GetDownloadUrlForLayer'
- 'ecr:GetAuthorizationToken'
Resource: '*'
ManagedPolicyArns:
- !Ref DiagnosticsMp
Ec2InstanceProfile:
Type: 'AWS::IAM::InstanceProfile'
Properties:
Path: /platforms/ecs/
Roles:
- !Ref Ec2Role
DatabaseSg:
Type: 'AWS::EC2::SecurityGroup'
Properties:
SecurityGroupIngress:
- IpProtocol: '-1'
SourceSecurityGroupId: !Ref DbTargetClusterSg
VpcId: !Ref VpcId
GroupDescription: RancherOS Database Security Group
DbTargetClusterSg:
Type: 'AWS::EC2::SecurityGroup'
Properties:
SecurityGroupIngress: []
VpcId: !Ref VpcId
GroupDescription: Security group for database security to allow ingress from.
ClusterSelfIngress:
Type: 'AWS::EC2::SecurityGroupIngress'
Properties:
GroupId: !Ref DbTargetClusterSg
IpProtocol: '-1'
SourceSecurityGroupId: !Ref DbTargetClusterSg
InstanceTerminateHook:
Type: "AWS::AutoScaling::LifecycleHook"
Properties:
AutoScalingGroupName: !Ref ClusterAutoScalingGroup
DefaultResult: ABANDON
HeartbeatTimeout: 900
LifecycleTransition: autoscaling:EC2_INSTANCE_TERMINATING
NotificationTargetARN: !Ref ScalingEvents
RoleARN: !GetAtt InstanceTerminateHookPermission.Arn
InstanceTerminateHookPermission:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: "Allow"
Principal:
Service:
- "autoscaling.amazonaws.com"
Action:
- "sts:AssumeRole"
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AutoScalingNotificationAccessRole
Path: "/"
ScalingEvents:
Type: "AWS::SNS::Topic"
Properties:
Subscription:
- Endpoint:
Fn::GetAtt: ["ScalingEventsProcessor", "Arn"]
Protocol: lambda
ScalingEventsProcessor:
Type: "AWS::Lambda::Function"
Properties:
Code:
S3Bucket: !If [IsLambdaBucketParamEmpty, !Sub "glenfiddich-${AWS::Region}", !Ref LambdaBucket]
S3Key: !Sub ${LambdaRootPath}ecs-drain-instance.zip
Handler: index.handler
Description: ECS scaling event processor
Role:
Fn::GetAtt: ["ScalingEventsProcessorPermission", "Arn"]
Runtime: nodejs12.x
Timeout: 900
Environment:
Variables:
CLUSTER_NAME: !Ref EcsCluster
ScalingEventsProcessorPermission:
Type: "AWS::IAM::Role"
Properties:
Policies:
-
PolicyName: "lambda-inline"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- autoscaling:CompleteLifecycleAction
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
- ec2:DescribeInstances
- ec2:DescribeInstanceAttribute
- ec2:DescribeInstanceStatus
- ec2:DescribeHosts
- ecs:ListContainerInstances
- ecs:SubmitContainerStateChange
- ecs:SubmitTaskStateChange
- ecs:DescribeContainerInstances
- ecs:UpdateContainerInstancesState
- ecs:ListTasks
- ecs:DescribeTasks
- sns:Publish
- sns:ListSubscriptions
Resource: "*"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service:
- "lambda.amazonaws.com"
Action:
- "sts:AssumeRole"
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AutoScalingNotificationAccessRole
Path: "/"
LambdaInvokePermission:
Type: "AWS::Lambda::Permission"
Properties:
FunctionName: !Ref ScalingEventsProcessor
Action: lambda:InvokeFunction
Principal: sns.amazonaws.com
SourceArn: !Ref ScalingEvents
LambdaSubscriptionToSNSTopic:
Type: AWS::SNS::Subscription
Properties:
Endpoint:
Fn::GetAtt: ["ScalingEventsProcessor", "Arn"]
Protocol: 'lambda'
TopicArn: !Ref ScalingEvents
# End of Instance Draining Handling
AsgScalingPolicy:
Type: AWS::AutoScaling::ScalingPolicy
Properties:
AutoScalingGroupName: !Ref ClusterAutoScalingGroup
PolicyType: TargetTrackingScaling
TargetTrackingConfiguration:
TargetValue: !Ref EcsCpuReservationTrackingTarget
CustomizedMetricSpecification:
Dimensions:
- Name: "ClusterName"
Value: !Ref "EcsCluster"
MetricName: "CPUReservation"
Statistic: "Maximum"
Namespace: "AWS/ECS"
# Shared Roles
# Role used for scheduling the ecs services and registering them with the loadbalancer
SharedEcsServiceSchedulingRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service:
- ecs.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /platforms/ecs-base/
Policies:
- PolicyName: ecs-service
PolicyDocument:
Statement:
- Effect: Allow
Action:
- 'elasticloadbalancing:DeregisterInstancesFromLoadBalancer'
- 'elasticloadbalancing:DeregisterTargets'
- 'elasticloadbalancing:Describe*'
- 'elasticloadbalancing:RegisterInstancesWithLoadBalancer'
- 'elasticloadbalancing:RegisterTargets'
- 'ec2:Describe*'
- 'ec2:AuthorizeSecurityGroupIngress'
Resource: '*'
# Role used for ecs service auto scaling
SharedEcsServiceScalingRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service:
- application-autoscaling.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /platforms/ecs-base/
Policies:
- PolicyName: ecs-service
PolicyDocument:
Statement:
- Effect: Allow
Action:
- 'ecs:DescribeServices'
- 'ecs:UpdateService'
- 'cloudwatch:DescribeAlarms'
Resource: '*'
# Role used for ecs service auto scaling
ShareEcsServiceTaskExecutionRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: [ecs-tasks.amazonaws.com]
Action: ['sts:AssumeRole']
Path: /platforms/ecs-base/
ManagedPolicyArns: ['arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy']
# Role used for ecs service auto scaling
ShareEcsServiceScheduleTaskRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: [events.amazonaws.com]
Action: ['sts:AssumeRole']
Path: /platforms/ecs-base/
Policies:
- PolicyName: ecs-runtask
PolicyDocument:
Statement:
- Effect: Allow
Action:
- 'ecs:RunTask'
Resource: '*'
Outputs:
EcsAdminUrl:
Description: Ec2 Container Service Cluster
Value: !Sub 'https://${AWS::Region}.console.aws.amazon.com/ecs/home?region=${AWS::Region}#/clusters/${EcsCluster}/containerInstances'
SharedScalingRole:
Value: !GetAtt SharedEcsServiceScalingRole.Arn
SharedSchedulingRole:
Value: !GetAtt SharedEcsServiceSchedulingRole.Arn
SharedTaskExecutionRole:
Value: !GetAtt ShareEcsServiceTaskExecutionRole.Arn
ShareScheduleTaskRole:
Value: !GetAtt ShareEcsServiceScheduleTaskRole.Arn
ClusterLaunchTemplateId:
Value: !Ref ClusterLaunchTemplate
ClusterLaunchTemplateVersion:
Value: !GetAtt ClusterLaunchTemplate.LatestVersionNumber