ECS container instance draining on lifecycle events
Overview
Automates Container Instance Draining in Amazon ECS by removing tasks from an instance before scaling down a cluster with Auto Scaling Groups. Heavily inspired by this blog post from AWS.
Lambda source code taken from and terraform inspired by the CloudFormation stack from Amazon available here.
It works by consuming lifecyle events from an autoscaling group. When an autoscaling:EC2_INSTANCE_TERMINATING event happens for the specified ASG it is placed on an SNS topic which in turn triggers lambda that will drain the tasks first from the ECS instance and then terminate the instance once the number of tasks on the instance become zero.