├── Architecture.png ├── LICENSE ├── NOTICE.txt ├── README.md └── cform └── ecs.yaml /Architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/ecs-cid-sample/0d60dd5f22c73c62b7ed1b0a931046b9bfd2dced/Architecture.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /NOTICE.txt: -------------------------------------------------------------------------------- 1 | AWS ECS Container instance draining integration with ASG hooks. 2 | 3 | Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ECS Container draining 2 | Amazon EC2 Container Service (Amazon ECS) is a container management service that makes it easy to run, stop, and manage Docker containers on a cluster of Amazon EC2 instances. When you run tasks using Amazon ECS, you place them on a cluster, which is a logical grouping of EC2 instances. Amazon ECS downloads your container images from a registry that you specify, and runs those images on the container instances within your cluster. 3 | 4 | There are times when EC2 instances need to be removed from the cluster, for example cluster scale-down or updating an AMI. Today we have delivered Container Instance Draining to simplify these scenarios. The draining state prevents new tasks from being started on the container instance, notifies the service scheduler to move tasks that are running on the instance to other instances in the cluster, and enables you to wait until tasks have successfully moved before terminating the instance. 5 | 6 | 7 | 8 | # Overview of steps 9 | 1. Download the CloudFormation template 10 | 11 | 2. Launch the CloudFormation template that creates the following AWS resources: 12 | 13 | * The VPC and associated network elements (subnets, security groups, route table, etc) 14 | * ECS Cluster, ECS service, a sample ECS task definition 15 | * Auto scaling group with two EC2 instances and a termination lifecycle hook 16 | * Lambda function, permissions to invoke lambda, and lambda execution roles 17 | * SNS topic, policy 18 | 19 | For the full solution overview visit [Blog link](https://aws.amazon.com/blogs/compute/how-to-automate-container-instance-draining-in-amazon-ecs). 20 | 21 | ## CloudFormation template 22 | - cform/ecs.yaml 23 | 24 | *** 25 | 26 | Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 27 | 28 | Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at 29 | 30 | http://aws.amazon.com/apache2.0/ 31 | 32 | or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 33 | -------------------------------------------------------------------------------- /cform/ecs.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Description: > 3 | AWS CloudFormation template to create a new VPC 4 | or use an existing VPC for ECS deployment 5 | in Create Cluster Wizard 6 | Parameters: 7 | EcsClusterName: 8 | Type: String 9 | Description: > 10 | Specifies the ECS Cluster Name with which the resources would be 11 | associated 12 | Default: 'demoCluster' 13 | KeyName: 14 | Type: String 15 | Description: > 16 | REQUIRED - Specifies the name of an existing Amazon EC2 key pair 17 | to enable SSH access to the EC2 instances in your cluster. 18 | EcsAmiId: 19 | Type: String 20 | Description: REQUIRED - Default ECS Optimized AMI for us-west-2 region. Please change it to reflect your regions' latest ECS AMI-ID 21 | Default: 'ami-8e7bc4ee' 22 | EcsInstanceType: 23 | Type: String 24 | Description: > 25 | Specifies the EC2 instance type for your container instances. 26 | Defaults to t2.medium 27 | Default: t2.medium 28 | ConstraintDescription: must be a valid EC2 instance type. 29 | VpcId: 30 | Type: String 31 | Description: > 32 | Optional - Specifies the ID of an existing VPC in which to launch 33 | your container instances. If you specify a VPC ID, you must specify a list of 34 | existing subnets in that VPC. If you do not specify a VPC ID, a new VPC is created 35 | with atleast 1 subnet. 36 | Default: '' 37 | AllowedPattern: "^(?:vpc-[0-9a-f]{8}|)$" 38 | ConstraintDescription: > 39 | VPC Id must begin with 'vpc-' or leave blank to have a 40 | new VPC created 41 | SubnetIds: 42 | Type: CommaDelimitedList 43 | Description: > 44 | Optional - Specifies the Comma separated list of existing VPC Subnet 45 | Ids where ECS instances will run 46 | Default: '' 47 | SecurityGroupId: 48 | Type: String 49 | Description: > 50 | Optional - Specifies the Security Group Id of an existing Security 51 | Group. Leave blank to have a new Security Group created 52 | Default: '' 53 | VpcCidr: 54 | Type: String 55 | Description: Optional - Specifies the CIDR Block of VPC 56 | Default: '10.0.0.0/16' 57 | SubnetCidr1: 58 | Type: String 59 | Description: Specifies the CIDR Block of Subnet 1 60 | Default: '10.0.0.0/24' 61 | SubnetCidr2: 62 | Type: String 63 | Description: Specifies the CIDR Block of Subnet 2 64 | Default: '10.0.1.0/24' 65 | SubnetCidr3: 66 | Type: String 67 | Description: Specifies the CIDR Block of Subnet 3 68 | Default: '' 69 | IamRoleInstanceProfile: 70 | Type: String 71 | Description: > 72 | Specifies the Name or the Amazon Resource Name (ARN) of the instance 73 | profile associated with the IAM role for the instance 74 | Default: 'ecsInstanceRole' 75 | SecurityIngressFromPort: 76 | Type: Number 77 | Description: > 78 | Optional - Specifies the Start of Security Group port to open on 79 | ECS instances - defaults to port 0 80 | Default: '80' 81 | SecurityIngressToPort: 82 | Type: Number 83 | Description: > 84 | Optional - Specifies the End of Security Group port to open on ECS 85 | instances - defaults to port 65535 86 | Default: '80' 87 | SecurityIngressCidrIp: 88 | Type: String 89 | Description: > 90 | Optional - Specifies the CIDR/IP range for Security Ports - defaults 91 | to 0.0.0.0/0 92 | Default: 0.0.0.0/0 93 | VpcAvailabilityZones: 94 | Type: CommaDelimitedList 95 | Description: > 96 | Specifies a comma-separated list of 3 VPC Availability Zones for 97 | the creation of new subnets. These zones must have the available status. 98 | Default: 'us-west-2b,us-west-2c,us-west-2a' 99 | EbsVolumeSize: 100 | Type: Number 101 | Description: > 102 | Optional - Specifies the Size in GBs, of the newly created Amazon 103 | Elastic Block Store (Amazon EBS) volume 104 | Default: '22' 105 | EbsVolumeType: 106 | Type: String 107 | Description: Optional - Specifies the Type of (Amazon EBS) volume 108 | Default: 'gp2' 109 | AllowedValues: 110 | - '' 111 | - standard 112 | - io1 113 | - gp2 114 | - sc1 115 | - st1 116 | ConstraintDescription: Must be a valid EC2 volume type. 117 | Conditions: 118 | CreateEC2LCWithKeyPair: 119 | !Not [!Equals [!Ref KeyName, '']] 120 | CreateNewSecurityGroup: 121 | !Equals [!Ref SecurityGroupId, ''] 122 | CreateNewVpc: 123 | !Equals [!Ref VpcId, ''] 124 | CreateSubnet1: !And 125 | - !Not [!Equals [!Ref SubnetCidr1, '']] 126 | - !Condition CreateNewVpc 127 | CreateSubnet2: !And 128 | - !Not [!Equals [!Ref SubnetCidr2, '']] 129 | - !Condition CreateSubnet1 130 | CreateSubnet3: !And 131 | - !Not [!Equals [!Ref SubnetCidr3, '']] 132 | - !Condition CreateSubnet2 133 | CreateEbsVolume: !And 134 | - !Not [!Equals [!Ref EbsVolumeSize, '0']] 135 | - !Not [!Equals [!Ref EbsVolumeType, '']] 136 | Resources: 137 | MyCluster: 138 | Type: "AWS::ECS::Cluster" 139 | Properties: 140 | ClusterName: !Ref EcsClusterName 141 | Vpc: 142 | Condition: CreateSubnet1 143 | Type: AWS::EC2::VPC 144 | Properties: 145 | CidrBlock: !Ref VpcCidr 146 | EnableDnsSupport: 'true' 147 | EnableDnsHostnames: 'true' 148 | PubSubnetAz1: 149 | Condition: CreateSubnet1 150 | Type: AWS::EC2::Subnet 151 | Properties: 152 | VpcId: !Ref Vpc 153 | CidrBlock: !Ref SubnetCidr1 154 | AvailabilityZone: !Select [ 0, !Ref VpcAvailabilityZones ] 155 | PubSubnetAz2: 156 | Condition: CreateSubnet2 157 | Type: AWS::EC2::Subnet 158 | Properties: 159 | VpcId: !Ref Vpc 160 | CidrBlock: !Ref SubnetCidr2 161 | AvailabilityZone: !Select [ 1, !Ref VpcAvailabilityZones ] 162 | PubSubnetAz3: 163 | Condition: CreateSubnet3 164 | Type: AWS::EC2::Subnet 165 | Properties: 166 | VpcId: !Ref Vpc 167 | CidrBlock: !Ref SubnetCidr3 168 | AvailabilityZone: !Select [ 2, !Ref VpcAvailabilityZones ] 169 | InternetGateway: 170 | Condition: CreateSubnet1 171 | Type: AWS::EC2::InternetGateway 172 | AttachGateway: 173 | Condition: CreateSubnet1 174 | Type: AWS::EC2::VPCGatewayAttachment 175 | Properties: 176 | VpcId: !Ref Vpc 177 | InternetGatewayId: !Ref InternetGateway 178 | RouteViaIgw: 179 | Condition: CreateSubnet1 180 | Type: AWS::EC2::RouteTable 181 | Properties: 182 | VpcId: !Ref Vpc 183 | PublicRouteViaIgw: 184 | Condition: CreateSubnet1 185 | Type: AWS::EC2::Route 186 | DependsOn: AttachGateway 187 | Properties: 188 | RouteTableId: !Ref RouteViaIgw 189 | DestinationCidrBlock: 0.0.0.0/0 190 | GatewayId: !Ref InternetGateway 191 | PubSubnet1RouteTableAssociation: 192 | Condition: CreateSubnet1 193 | Type: AWS::EC2::SubnetRouteTableAssociation 194 | Properties: 195 | SubnetId: !Ref PubSubnetAz1 196 | RouteTableId: !Ref RouteViaIgw 197 | PubSubnet2RouteTableAssociation: 198 | Condition: CreateSubnet2 199 | Type: AWS::EC2::SubnetRouteTableAssociation 200 | Properties: 201 | SubnetId: !Ref PubSubnetAz2 202 | RouteTableId: !Ref RouteViaIgw 203 | PubSubnet3RouteTableAssociation: 204 | Condition: CreateSubnet3 205 | Type: AWS::EC2::SubnetRouteTableAssociation 206 | Properties: 207 | SubnetId: !Ref PubSubnetAz3 208 | RouteTableId: !Ref RouteViaIgw 209 | EcsSecurityGroup: 210 | Condition: CreateNewSecurityGroup 211 | Type: AWS::EC2::SecurityGroup 212 | Properties: 213 | GroupDescription: ECS Allowed Ports 214 | VpcId: !If [ CreateSubnet1, !Ref Vpc, !Ref VpcId ] 215 | SecurityGroupIngress: 216 | IpProtocol: tcp 217 | FromPort: !Ref SecurityIngressFromPort 218 | ToPort: !Ref SecurityIngressToPort 219 | CidrIp: !Ref SecurityIngressCidrIp 220 | EcsInstanceLc: 221 | Type: AWS::AutoScaling::LaunchConfiguration 222 | Properties: 223 | ImageId: !Ref EcsAmiId 224 | InstanceType: !Ref EcsInstanceType 225 | AssociatePublicIpAddress: true 226 | IamInstanceProfile: !Ref IamRoleInstanceProfile 227 | KeyName: !If [ CreateEC2LCWithKeyPair, !Ref KeyName, !Ref "AWS::NoValue" ] 228 | SecurityGroups: [ !If [ CreateNewSecurityGroup, !Ref EcsSecurityGroup, !Ref SecurityGroupId ] ] 229 | BlockDeviceMappings: 230 | - DeviceName: "/dev/sdm" 231 | Ebs: 232 | VolumeType: "gp2" 233 | Iops: "200" 234 | DeleteOnTermination: "true" 235 | VolumeSize: "20" 236 | UserData: 237 | Fn::Base64: !Sub | 238 | #!/bin/bash 239 | echo ECS_CLUSTER=${EcsClusterName} >> /etc/ecs/ecs.config 240 | EcsInstanceAsg: 241 | Type: AWS::AutoScaling::AutoScalingGroup 242 | Properties: 243 | VPCZoneIdentifier: !If 244 | - CreateSubnet1 245 | - !If 246 | - CreateSubnet2 247 | - !If 248 | - CreateSubnet3 249 | - [ !Sub "${PubSubnetAz1}, ${PubSubnetAz2}, ${PubSubnetAz3}" ] 250 | - [ !Sub "${PubSubnetAz1}, ${PubSubnetAz2}" ] 251 | - [ !Sub "${PubSubnetAz1}" ] 252 | - !Ref SubnetIds 253 | LaunchConfigurationName: !Ref EcsInstanceLc 254 | MinSize: '0' 255 | MaxSize: '3' 256 | DesiredCapacity: '3' 257 | NotificationConfigurations: 258 | - TopicARN: !Ref ASGSNSTopic 259 | NotificationTypes: 260 | - autoscaling:EC2_INSTANCE_TERMINATE 261 | Tags: 262 | - 263 | Key: Name 264 | Value: !Sub "ECS Instance - ${AWS::StackName}" 265 | PropagateAtLaunch: 'true' 266 | - 267 | Key: Description 268 | Value: > 269 | This instance is the part of the Auto Scaling group which was created 270 | through ECS Console 271 | PropagateAtLaunch: 'true' 272 | taskdefinition: 273 | Type: "AWS::ECS::TaskDefinition" 274 | Properties: 275 | ContainerDefinitions: 276 | - 277 | Name: "ecs-sample-app" 278 | MountPoints: 279 | - 280 | SourceVolume: "my-vol" 281 | ContainerPath: "/var/www/my-vol" 282 | Image: "amazon/amazon-ecs-sample" 283 | Cpu: "10" 284 | PortMappings: 285 | - 286 | ContainerPort: "80" 287 | HostPort: "80" 288 | EntryPoint: 289 | - "/usr/sbin/apache2" 290 | - "-D" 291 | - "FOREGROUND" 292 | Memory: "500" 293 | Essential: "true" 294 | - 295 | Name: "busybox" 296 | Image: "busybox" 297 | Cpu: "10" 298 | EntryPoint: 299 | - "sh" 300 | - "-c" 301 | Memory: "500" 302 | Command: 303 | - "/bin/sh -c \"while true; do /bin/date > /var/www/my-vol/date; sleep 1; done\"" 304 | Essential: "false" 305 | VolumesFrom: 306 | - 307 | SourceContainer: "ecs-sample-app" 308 | Volumes: 309 | - 310 | Host: 311 | SourcePath: "/var/lib/docker/vfs/dir/" 312 | Name: "my-vol" 313 | demoService: 314 | Type: "AWS::ECS::Service" 315 | Properties: 316 | Cluster: !Ref MyCluster 317 | DeploymentConfiguration: 318 | MaximumPercent: 100 319 | MinimumHealthyPercent: 50 320 | DesiredCount: 2 321 | TaskDefinition: !Ref taskdefinition 322 | DependsOn: 323 | - ECSServiceRole 324 | - taskdefinition 325 | ECSServiceRole: 326 | Type: AWS::IAM::Role 327 | Properties: 328 | AssumeRolePolicyDocument: 329 | Statement: 330 | - Effect: Allow 331 | Principal: 332 | Service: 333 | - ecs.amazonaws.com 334 | Action: 335 | - sts:AssumeRole 336 | Path: "/" 337 | Policies: 338 | - PolicyName: ecs-service 339 | PolicyDocument: 340 | Statement: 341 | - Effect: Allow 342 | Action: 343 | - elasticloadbalancing:Describe* 344 | - elasticloadbalancing:DeregisterInstancesFromLoadBalancer 345 | - elasticloadbalancing:RegisterInstancesWithLoadBalancer 346 | - ec2:Describe* 347 | - ec2:AuthorizeSecurityGroupIngress 348 | Resource: "*" 349 | SNSLambdaRole: 350 | Type: "AWS::IAM::Role" 351 | Properties: 352 | AssumeRolePolicyDocument: 353 | Version: "2012-10-17" 354 | Statement: 355 | - 356 | Effect: "Allow" 357 | Principal: 358 | Service: 359 | - "autoscaling.amazonaws.com" 360 | Action: 361 | - "sts:AssumeRole" 362 | ManagedPolicyArns: 363 | - arn:aws:iam::aws:policy/service-role/AutoScalingNotificationAccessRole 364 | Path: "/" 365 | LambdaExecutionRole: 366 | Type: "AWS::IAM::Role" 367 | Properties: 368 | Policies: 369 | - 370 | PolicyName: "lambda-inline" 371 | PolicyDocument: 372 | Version: "2012-10-17" 373 | Statement: 374 | - Effect: "Allow" 375 | Action: 376 | - autoscaling:CompleteLifecycleAction 377 | - logs:CreateLogGroup 378 | - logs:CreateLogStream 379 | - logs:PutLogEvents 380 | - ecs:ListContainerInstances 381 | - ecs:DescribeContainerInstances 382 | - ecs:UpdateContainerInstancesState 383 | - sns:Publish 384 | Resource: "*" 385 | AssumeRolePolicyDocument: 386 | Version: "2012-10-17" 387 | Statement: 388 | - 389 | Effect: "Allow" 390 | Principal: 391 | Service: 392 | - "lambda.amazonaws.com" 393 | Action: 394 | - "sts:AssumeRole" 395 | ManagedPolicyArns: 396 | - arn:aws:iam::aws:policy/service-role/AutoScalingNotificationAccessRole 397 | Path: "/" 398 | ASGSNSTopic: 399 | Type: "AWS::SNS::Topic" 400 | Properties: 401 | Subscription: 402 | - 403 | Endpoint: 404 | Fn::GetAtt: 405 | - "LambdaFunctionForASG" 406 | - "Arn" 407 | Protocol: "lambda" 408 | DependsOn: "LambdaFunctionForASG" 409 | LambdaFunctionForASG: 410 | Type: "AWS::Lambda::Function" 411 | Properties: 412 | Description: Gracefully drain ECS tasks from EC2 instances before the instances are 413 | terminated by autoscaling. 414 | Handler: index.lambda_handler 415 | Role: !GetAtt LambdaExecutionRole.Arn 416 | Runtime: python3.6 417 | MemorySize: 128 418 | Timeout: 60 419 | Code: 420 | ZipFile: !Sub | 421 | import json 422 | import time 423 | import boto3 424 | 425 | CLUSTER = '${EcsClusterName}' 426 | REGION = '${AWS::Region}' 427 | 428 | ECS = boto3.client('ecs', region_name=REGION) 429 | ASG = boto3.client('autoscaling', region_name=REGION) 430 | SNS = boto3.client('sns', region_name=REGION) 431 | 432 | def find_ecs_instance_info(instance_id): 433 | paginator = ECS.get_paginator('list_container_instances') 434 | for list_resp in paginator.paginate(cluster=CLUSTER): 435 | arns = list_resp['containerInstanceArns'] 436 | desc_resp = ECS.describe_container_instances(cluster=CLUSTER, 437 | containerInstances=arns) 438 | for container_instance in desc_resp['containerInstances']: 439 | if container_instance['ec2InstanceId'] != instance_id: 440 | continue 441 | 442 | print('Found instance: id=%s, arn=%s, status=%s, runningTasksCount=%s' % 443 | (instance_id, container_instance['containerInstanceArn'], 444 | container_instance['status'], container_instance['runningTasksCount'])) 445 | 446 | return (container_instance['containerInstanceArn'], 447 | container_instance['status'], container_instance['runningTasksCount']) 448 | 449 | return None, None, 0 450 | 451 | def instance_has_running_tasks(instance_id): 452 | (instance_arn, container_status, running_tasks) = find_ecs_instance_info(instance_id) 453 | if instance_arn is None: 454 | print('Could not find instance ID %s. Letting autoscaling kill the instance.' % 455 | (instance_id)) 456 | return False 457 | 458 | if container_status != 'DRAINING': 459 | print('Setting container instance %s (%s) to DRAINING' % 460 | (instance_id, instance_arn)) 461 | ECS.update_container_instances_state(cluster=CLUSTER, 462 | containerInstances=[instance_arn], 463 | status='DRAINING') 464 | 465 | return running_tasks > 0 466 | 467 | def lambda_handler(event, context): 468 | msg = json.loads(event['Records'][0]['Sns']['Message']) 469 | 470 | if 'LifecycleTransition' not in msg.keys() or \ 471 | msg['LifecycleTransition'].find('autoscaling:EC2_INSTANCE_TERMINATING') == -1: 472 | print('Exiting since the lifecycle transition is not EC2_INSTANCE_TERMINATING.') 473 | return 474 | 475 | if instance_has_running_tasks(msg['EC2InstanceId']): 476 | print('Tasks are still running on instance %s; posting msg to SNS topic %s' % 477 | (msg['EC2InstanceId'], event['Records'][0]['Sns']['TopicArn'])) 478 | time.sleep(5) 479 | sns_resp = SNS.publish(TopicArn=event['Records'][0]['Sns']['TopicArn'], 480 | Message=json.dumps(msg), 481 | Subject='Publishing SNS msg to invoke Lambda again.') 482 | print('Posted msg %s to SNS topic.' % (sns_resp['MessageId'])) 483 | else: 484 | print('No tasks are running on instance %s; setting lifecycle to complete' % 485 | (msg['EC2InstanceId'])) 486 | 487 | ASG.complete_lifecycle_action(LifecycleHookName=msg['LifecycleHookName'], 488 | AutoScalingGroupName=msg['AutoScalingGroupName'], 489 | LifecycleActionResult='CONTINUE', 490 | InstanceId=msg['EC2InstanceId']) 491 | LambdaInvokePermission: 492 | Type: "AWS::Lambda::Permission" 493 | Properties: 494 | FunctionName: !Ref LambdaFunctionForASG 495 | Action: lambda:InvokeFunction 496 | Principal: "sns.amazonaws.com" 497 | SourceArn: !Ref ASGSNSTopic 498 | LambdaSubscriptionToSNSTopic: 499 | Type: AWS::SNS::Subscription 500 | Properties: 501 | Endpoint: 502 | Fn::GetAtt: 503 | - "LambdaFunctionForASG" 504 | - "Arn" 505 | Protocol: 'lambda' 506 | TopicArn: !Ref ASGSNSTopic 507 | ASGTerminateHook: 508 | Type: "AWS::AutoScaling::LifecycleHook" 509 | Properties: 510 | AutoScalingGroupName: !Ref EcsInstanceAsg 511 | DefaultResult: "ABANDON" 512 | HeartbeatTimeout: "900" 513 | LifecycleTransition: "autoscaling:EC2_INSTANCE_TERMINATING" 514 | NotificationTargetARN: !Ref ASGSNSTopic 515 | RoleARN: 516 | Fn::GetAtt: 517 | - "SNSLambdaRole" 518 | - "Arn" 519 | DependsOn: "ASGSNSTopic" 520 | Outputs: 521 | EcsInstanceAsgName: 522 | Description: Auto Scaling Group Name for ECS Instances 523 | Value: !Ref EcsInstanceAsg 524 | SNSTopicForASG: 525 | Description: Topic used by ASG to send notifications when instance state is changing 526 | Value: !Ref ASGSNSTopic 527 | --------------------------------------------------------------------------------