├── .github └── workflows │ ├── goreleaser.yml │ └── test.yml ├── .gitignore ├── .goreleaser.yml ├── LICENSE ├── Makefile ├── README.md ├── cmd └── drain │ └── main.go ├── ecs.go ├── ecs_test.go ├── events-samples ├── asg-terminate-hook.json └── spot-interruption.json ├── go.mod ├── go.sum ├── handler.go ├── renovate.json └── serverless.yml /.github/workflows/goreleaser.yml: -------------------------------------------------------------------------------- 1 | name: goreleaser 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | 8 | jobs: 9 | goreleaser: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - 13 | name: Checkout 14 | uses: actions/checkout@v4 15 | with: 16 | fetch-depth: 0 17 | - 18 | name: Set up Go 19 | uses: actions/setup-go@v5 20 | with: 21 | go-version: 'stable' 22 | - 23 | name: Run GoReleaser 24 | uses: goreleaser/goreleaser-action@v6 25 | with: 26 | version: latest 27 | args: release --rm-dist 28 | env: 29 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 30 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: 3 | push: 4 | branches: 5 | - master 6 | pull_request: 7 | branches: 8 | - master 9 | jobs: 10 | test: 11 | strategy: 12 | fail-fast: false 13 | matrix: 14 | go-version: ['oldstable', 'stable'] 15 | platform: [ubuntu-latest] 16 | runs-on: ${{ matrix.platform }} 17 | steps: 18 | 19 | - name: Install Go 20 | uses: actions/setup-go@v5 21 | with: 22 | go-version: ${{ matrix.go-version }} 23 | 24 | - name: Checkout code 25 | uses: actions/checkout@v4 26 | 27 | - name: Test 28 | run: go test ./... 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .serverless 2 | /bin -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | builds: 2 | - main: ./cmd/drain/main.go 3 | # build for lambda env only 4 | goarch: 5 | - amd64 6 | goos: 7 | - linux 8 | env: 9 | - CGO_ENABLED=0 10 | archives: 11 | - format: zip 12 | # https://goreleaser.com/customization/archive/#packaging-only-the-binaries 13 | files: 14 | - none* 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | GOOS=linux 2 | GOARCH ?= amd64 3 | CGO_ENABLED=0 4 | export 5 | 6 | build: 7 | go build -tags lambda.norpc -o bootstrap cmd/drain/main.go 8 | @du -h bootstrap 9 | 10 | deploy: build 11 | sls deploy -v 12 | 13 | outdated-deps: ## get list of outdated direct dependencies 14 | @go list -u -f '{{if and (.Update) (not .Indirect)}}{{.}}{{end}}' -m all 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ecs-drain-lambda 2 | 3 | Based on the original idea from [AWS Blog post](https://aws.amazon.com/ru/blogs/compute/how-to-automate-container-instance-draining-in-amazon-ecs/) and [GitHub](https://github.com/aws-samples/ecs-cid-sample). With the following differences: 4 | 5 | - Autoscaling Hooks events are received via CloudWatch rules, which makes possible having one function for draining many ECS Clusters 6 | 7 | - [Serverless Framework](https://github.com/serverless/serverless) based 8 | 9 | - Written in Golang 10 | 11 | - Supports the draining of Spot based ECS instances via [Spot Instance Interruption Notice](https://docs.aws.amazon.com/en_us/AWSEC2/latest/UserGuide/spot-interruptions.html#spot-instance-termination-notices) 12 | 13 | ## Why? 14 | 15 | When updating AMI for the ECS instances then ASG replaces them without ["Draining"](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/container-instance-draining.html) , which may cause a short downtime of deployed containers. This function automates the ECS Cluster Instances Drain process. 16 | 17 | ## How does it work? 18 | 19 | *ecs-drain-lambda* function: 20 | 21 | - Receives CloudWatch event: 22 | 23 | - **ANY** AutoScaling Lifecycle Terminate event ( ***[EC2 Auto Scaling Lifecycle Hooks](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html) for `autoscaling:EC2_INSTANCE_TERMINATING` event should be configured on your ASG*** ) from CloudWatch Events 24 | 25 | or 26 | 27 | - **ANY** [Spot Instance Interruption Notice](https://docs.aws.amazon.com/en_us/AWSEC2/latest/UserGuide/spot-interruptions.html#spot-instance-termination-notices). Imporatant, AWS doesn't guarantees that instance will be drained in time, instance could be terminated before the notice arrival. 28 | 29 | - Gets the ID of the instance that has to be terminated 30 | 31 | - Looks for the ECS Cluster name in the UserData in the following format: `ECS_CLUSTER=xxxxxxxxx` 32 | 33 | - If some ECS Tasks are running on the instance, starts the `Drain` process 34 | 35 | - Waits for all the ECS Tasks to shutdown 36 | 37 | - [Completes Lifecycle Hook](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html#completing-lifecycle-hooks), which lets ASG proceed with instance termination 38 | 39 | ## Requirements 40 | 41 | - [Serverless Framework](https://github.com/serverless/serverless) 42 | 43 | - [Golang](https://golang.org/doc/install) 44 | 45 | - GNU Make 46 | 47 | - Configured [EC2 Auto Scaling Lifecycle Hooks](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html) for `autoscaling:EC2_INSTANCE_TERMINATING` event on your ASG 48 | 49 | Example CloudFormation resource: 50 | 51 | ASGTerminateHook: 52 | Type: "AWS::AutoScaling::LifecycleHook" 53 | Properties: 54 | AutoScalingGroupName: !Ref ECSAutoScalingGroup 55 | DefaultResult: "ABANDON" 56 | HeartbeatTimeout: "900" 57 | LifecycleTransition: "autoscaling:EC2_INSTANCE_TERMINATING" 58 | 59 | ## How to use 60 | 61 | - Clone the repo with `git clone` 62 | 63 | - Enter the project directory `cd ecs-drain-lambda` 64 | 65 | - Run `make deploy` 66 | 67 | **Note**: by default `us-east-1` region is selected, if you need to deploy it to the 68 | different region you can use `sls deploy -v --region ${AWS_REGION}` 69 | 70 | ## Deploy with Terraform 71 | 72 | If you want to deploy *ecs-drain-lambda* function with Terraform, there is [ecs-drain-lambda](https://registry.terraform.io/modules/nabeken/ecs-drain-lambda/aws/latest) Terraform Module. 73 | 74 | ## Limitations 75 | 76 | - Function waits for 15 minutes for Drain to complete and fails with the timeout after 77 | 78 | - If function fails, then the default lifecycle hook action will be triggered (`ABANDON` or `CONTINUE` depending on your Hook configuration), either result will end up with eventual instance termination. 79 | 80 | [Documentation](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html#lifecycle-hook-considerations) 81 | 82 | If the instance is terminating, both ABANDON and CONTINUE allow the instance to terminate. However, ABANDON stops any remaining actions, such as other lifecycle hooks, while CONTINUE allows any other lifecycle hooks to complete. 83 | -------------------------------------------------------------------------------- /cmd/drain/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/aws/aws-lambda-go/lambda" 5 | drain "github.com/getsocial-rnd/ecs-drain-lambda" 6 | ) 7 | 8 | func main() { 9 | lambda.Start(drain.HandleRequest) 10 | } 11 | -------------------------------------------------------------------------------- /ecs.go: -------------------------------------------------------------------------------- 1 | package drain 2 | 3 | import ( 4 | "encoding/base64" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "regexp" 9 | "time" 10 | 11 | "github.com/aws/aws-sdk-go/aws" 12 | "github.com/aws/aws-sdk-go/aws/session" 13 | "github.com/aws/aws-sdk-go/service/ec2" 14 | "github.com/aws/aws-sdk-go/service/ecs" 15 | ) 16 | 17 | var ( 18 | ecsClient = ecs.New(session.New()) 19 | ec2client = ec2.New(session.New()) 20 | ecsRegExp = regexp.MustCompile(`ECS_CLUSTER=([0-9A-Za-z_\-]*)`) 21 | ErrMissingUserData = errors.New("This instance seems not to have UserData") 22 | ErrMissingECSClusterInUserData = errors.New("This instance seems not to have EcsCluster definition in UserData") 23 | ErrInstanceTerminated = errors.New("This instance is already terminated") 24 | ) 25 | 26 | func Drain(ecsCluster, ec2Instance string) error { 27 | // Getting ECS Container instance representation by EC2 instance ID 28 | instance, err := getContainerInstance(ecsCluster, ec2Instance) 29 | if err != nil { 30 | return err 31 | } 32 | 33 | printJSON("Container instance", instance) 34 | 35 | var tasksToShutdownCount int64 36 | if instance != nil && instance.RunningTasksCount != nil { 37 | tasksToShutdownCount = *instance.RunningTasksCount 38 | } 39 | 40 | var runningTaskArns []*string 41 | // if we have some tasks running on the instance 42 | // we need to drain it and wait for all tasks to shutdown 43 | for tasksToShutdownCount > 0 { 44 | // if instance not being drained yet, 45 | // start the drain 46 | if *instance.Status != ecs.ContainerInstanceStatusDraining { 47 | fmt.Println("Starting draining and waiting for all tasks to shutdown") 48 | _, err := ecsClient.UpdateContainerInstancesState(&ecs.UpdateContainerInstancesStateInput{ 49 | Cluster: &ecsCluster, 50 | ContainerInstances: []*string{instance.ContainerInstanceArn}, 51 | Status: aws.String(ecs.ContainerInstanceStatusDraining), 52 | }) 53 | if err != nil { 54 | return err 55 | } 56 | 57 | // fetch list of tasks running on that instance 58 | resp, err := ecsClient.ListTasks(&ecs.ListTasksInput{ 59 | ContainerInstance: instance.ContainerInstanceArn, 60 | Cluster: &ecsCluster, 61 | }) 62 | if err != nil { 63 | return err 64 | } 65 | if resp != nil { 66 | runningTaskArns = resp.TaskArns 67 | } 68 | 69 | // update instance information, to be sure that it started draining 70 | instance, err = getContainerInstance(ecsCluster, ec2Instance) 71 | if err != nil { 72 | return err 73 | } 74 | } 75 | 76 | if len(runningTaskArns) == 0 { 77 | fmt.Println("no running tasks found") 78 | break 79 | } 80 | 81 | // monitor status of the tasks running on the current instance 82 | tasks, err := ecsClient.DescribeTasks(&ecs.DescribeTasksInput{ 83 | Cluster: &ecsCluster, 84 | Tasks: runningTaskArns, 85 | }) 86 | if err != nil { 87 | return err 88 | } 89 | 90 | if tasks == nil || len(tasks.Tasks) == 0 { 91 | fmt.Println("no tasks found") 92 | } 93 | 94 | taskStates := map[string]int{} 95 | tasksToShutdownCount = 0 96 | 97 | for _, task := range tasks.Tasks { 98 | // wait explicitly for tasks to become "STOPPED" 99 | // other way we may stop the instance with the tasks that 100 | // are still being in the "DEACTIVATING" state 101 | // see https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-lifecycle.html 102 | if task.LastStatus == nil { 103 | continue 104 | } 105 | 106 | taskStates[*task.LastStatus]++ 107 | if *task.LastStatus != ecs.DesiredStatusStopped { 108 | tasksToShutdownCount++ 109 | } 110 | } 111 | 112 | printJSON("Instance task states", taskStates) 113 | time.Sleep(10 * time.Second) 114 | } 115 | 116 | fmt.Println("Drain finished") 117 | return nil 118 | } 119 | 120 | func getContainerInstance(ecsCluster, ec2Instance string) (*ecs.ContainerInstance, error) { 121 | var containerInstances []*ecs.ContainerInstance 122 | 123 | err := ecsClient.ListContainerInstancesPages(&ecs.ListContainerInstancesInput{Cluster: &ecsCluster}, func(page *ecs.ListContainerInstancesOutput, lastPage bool) bool { 124 | respInstances, err := ecsClient.DescribeContainerInstances(&ecs.DescribeContainerInstancesInput{ 125 | Cluster: &ecsCluster, 126 | ContainerInstances: page.ContainerInstanceArns, 127 | }) 128 | 129 | if err != nil { 130 | fmt.Printf("Error describing container instances: %s", err) 131 | return false 132 | } 133 | 134 | containerInstances = append(containerInstances, respInstances.ContainerInstances...) 135 | return !lastPage 136 | }) 137 | 138 | if err != nil { 139 | return nil, err 140 | } 141 | 142 | for _, i := range containerInstances { 143 | if *i.Ec2InstanceId == ec2Instance { 144 | return i, nil 145 | } 146 | } 147 | return nil, fmt.Errorf("%q not found in the cluster %q", ec2Instance, ecsCluster) 148 | } 149 | 150 | func GetClusterNameFromInstanceUserData(ec2Instance string) (string, error) { 151 | // check instance state, error if already terminated 152 | resp, err := ec2client.DescribeInstances(&ec2.DescribeInstancesInput{ 153 | InstanceIds: []*string{&ec2Instance}, 154 | }) 155 | if err != nil { 156 | return "", err 157 | } 158 | 159 | if len(resp.Reservations) > 0 && len(resp.Reservations[0].Instances) > 0 { 160 | switch *resp.Reservations[0].Instances[0].State.Name { 161 | case ec2.InstanceStateNameTerminated, ec2.InstanceStateNameShuttingDown: 162 | return "", ErrInstanceTerminated 163 | } 164 | } 165 | 166 | att, err := ec2client.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{ 167 | InstanceId: &ec2Instance, 168 | Attribute: aws.String("userData"), 169 | }) 170 | if err != nil { 171 | return "", err 172 | } 173 | 174 | // checking if we got some user data, 175 | // if we found none, then instance probably not a part of ECS Cluster 176 | if att == nil || att.UserData == nil || att.UserData.Value == nil { 177 | return "", ErrMissingUserData 178 | } 179 | 180 | decodedUserData, err := base64.StdEncoding.DecodeString(*att.UserData.Value) 181 | if err != nil { 182 | return "", err 183 | } 184 | 185 | // Using RegExp to get actual ECS Cluster name from UserData string 186 | val, err := parseECSClusterValue(string(decodedUserData)) 187 | if err != nil { 188 | return "", err 189 | } 190 | 191 | return val, nil 192 | } 193 | 194 | // Fetch value of ECS_CLUSTER variable with the regexp 195 | func parseECSClusterValue(str string) (string, error) { 196 | m := ecsRegExp.FindAllStringSubmatch(str, -1) 197 | if len(m) == 0 || len(m[0]) < 2 { 198 | fmt.Printf("UserData:\n%s\n", str) 199 | return "", ErrMissingECSClusterInUserData 200 | } 201 | 202 | return m[0][1], nil 203 | } 204 | 205 | // AWS CloudWatch Logs prints only JSONs nicely 206 | func printJSON(text string, data interface{}) { 207 | if b, err := json.Marshal(data); err == nil { 208 | fmt.Println(text, string(b)) 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /ecs_test.go: -------------------------------------------------------------------------------- 1 | package drain 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestECSVariable(t *testing.T) { 9 | var testcases = []struct { 10 | testString string 11 | expectedValue string 12 | expectedError error 13 | }{ 14 | { 15 | testString: `echo "ECS_CLUSTER=test-ecs-cluster123" >> /etc/ecs/ecs.config`, 16 | expectedValue: "test-ecs-cluster123", 17 | }, 18 | { 19 | testString: `echo 'ECS_CLUSTER=test-ecs-cluster123' >> /etc/ecs/ecs.config`, 20 | expectedValue: "test-ecs-cluster123", 21 | }, 22 | { 23 | testString: `echo ECS_CLUSTER=test-ecs-cluster123 >> /etc/ecs/ecs.config`, 24 | expectedValue: "test-ecs-cluster123", 25 | }, 26 | { 27 | testString: `#!/bin/bash -xe 28 | echo ECS_CLUSTER=test-ecs-cluster123 >> /etc/ecs/ecs.config`, 29 | expectedValue: "test-ecs-cluster123", 30 | }, 31 | { 32 | testString: ` 33 | write_files: 34 | - path: /etc/ecs/ecs.config 35 | append: true 36 | content: | 37 | ECS_CLUSTER=my-super-ECS-cluster-22abc 38 | ECS_CONTAINER_STOP_TIMEOUT=2m 39 | `, 40 | expectedValue: "my-super-ECS-cluster-22abc", 41 | }, 42 | { 43 | testString: ` 44 | write_files: 45 | - path: /etc/ecs/ecs.config 46 | append: true 47 | content: | 48 | ECS_CONTAINER_STOP_TIMEOUT=2m 49 | `, 50 | expectedError: ErrMissingECSClusterInUserData, 51 | }, 52 | { 53 | testString: "", 54 | expectedError: ErrMissingECSClusterInUserData, 55 | }, 56 | { 57 | testString: ` 58 | pip install awscli 59 | aws configure set default.region ${AWS::Region} 60 | echo ECS_CLUSTER=my-super-ECS-cluster-22abc >> /etc/ecs/ecs.config 61 | `, 62 | expectedValue: "my-super-ECS-cluster-22abc", 63 | }, 64 | } 65 | 66 | for i, tst := range testcases { 67 | t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { 68 | val, err := parseECSClusterValue(tst.testString) 69 | if err != tst.expectedError { 70 | t.Errorf("Expected %v error, but got %v", tst.expectedError, err) 71 | } 72 | 73 | if val != tst.expectedValue { 74 | t.Errorf("Expected %q value, but got %q", tst.expectedValue, val) 75 | } 76 | }) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /events-samples/asg-terminate-hook.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0", 3 | "id": "468fe059-f4b7-445f-bb22-2a271b94974d", 4 | "detail-type": "EC2 Instance-terminate Lifecycle Action", 5 | "source": "aws.autoscaling", 6 | "account": "123456789012", 7 | "time": "2015-12-22T18:43:48Z", 8 | "region": "us-east-1", 9 | "resources": ["arn:aws:autoscaling:us-east-1:123456789012:autoScalingGroup:59fcbb81-bd02-485d-80ce-563ef5b237bf:autoScalingGroupName/sampleASG"], 10 | "detail": { 11 | "LifecycleActionToken": "630aa23f-48eb-45e7-aba6-799ea6093a0f", 12 | "AutoScalingGroupName": "sampleASG", 13 | "LifecycleHookName": "SampleLifecycleHook-6789", 14 | "EC2InstanceId": "i-12345678", 15 | "LifecycleTransition": "autoscaling:EC2_INSTANCE_TERMINATING" 16 | } 17 | } -------------------------------------------------------------------------------- /events-samples/spot-interruption.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0", 3 | "id": "1e5527d7-bb36-4607-3370-4164db56a40e", 4 | "detail-type": "EC2 Spot Instance Interruption Warning", 5 | "source": "aws.ec2", 6 | "account": "123456789012", 7 | "time": "1970-01-01T00:00:00Z", 8 | "region": "us-east-1", 9 | "resources": ["arn:aws:ec2:us-east-1b:instance/i-0b662ef9931388ba0"], 10 | "detail": { 11 | "instance-id": "i-0b662ef9931388ba0", 12 | "instance-action": "terminate" 13 | } 14 | } -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/getsocial-rnd/ecs-drain-lambda 2 | 3 | go 1.15 4 | 5 | require ( 6 | github.com/aws/aws-lambda-go v1.48.0 7 | github.com/aws/aws-sdk-go v1.55.6 8 | github.com/kr/pretty v0.3.1 // indirect 9 | github.com/rogpeppe/go-internal v1.12.0 // indirect 10 | github.com/stretchr/testify v1.8.4 // indirect 11 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect 12 | gopkg.in/yaml.v2 v2.4.0 // indirect 13 | ) 14 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/aws/aws-lambda-go v1.47.0 h1:0H8s0vumYx/YKs4sE7YM0ktwL2eWse+kfopsRI1sXVI= 2 | github.com/aws/aws-lambda-go v1.47.0/go.mod h1:dpMpZgvWx5vuQJfBt0zqBha60q7Dd7RfgJv23DymV8A= 3 | github.com/aws/aws-lambda-go v1.48.0 h1:1aZUYsrJu0yo5fC4z+Rba1KhNImXcJcvHu763BxoyIo= 4 | github.com/aws/aws-lambda-go v1.48.0/go.mod h1:dpMpZgvWx5vuQJfBt0zqBha60q7Dd7RfgJv23DymV8A= 5 | github.com/aws/aws-sdk-go v1.55.5 h1:KKUZBfBoyqy5d3swXyiC7Q76ic40rYcbqH7qjh59kzU= 6 | github.com/aws/aws-sdk-go v1.55.5/go.mod h1:eRwEWoyTWFMVYVQzKMNHWP5/RV4xIUGMQfXQHfHkpNU= 7 | github.com/aws/aws-sdk-go v1.55.6 h1:cSg4pvZ3m8dgYcgqB97MrcdjUmZ1BeMYKUxMMB89IPk= 8 | github.com/aws/aws-sdk-go v1.55.6/go.mod h1:eRwEWoyTWFMVYVQzKMNHWP5/RV4xIUGMQfXQHfHkpNU= 9 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= 10 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 11 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 12 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 13 | github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= 14 | github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= 15 | github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= 16 | github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= 17 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= 18 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 19 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 20 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 21 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 22 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 23 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 24 | github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= 25 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 26 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 27 | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= 28 | github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= 29 | github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= 30 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 31 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 32 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 33 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 34 | github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= 35 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 36 | github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= 37 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 38 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 39 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 40 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 41 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 42 | golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 43 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 44 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 45 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= 46 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 47 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 48 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 49 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 50 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 51 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 52 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 53 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 54 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 55 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 56 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 57 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 58 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 59 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 60 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 61 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 62 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 63 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 64 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 65 | gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 66 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= 67 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 68 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 69 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 70 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 71 | -------------------------------------------------------------------------------- /handler.go: -------------------------------------------------------------------------------- 1 | package drain 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | 8 | "github.com/aws/aws-lambda-go/events" 9 | "github.com/aws/aws-sdk-go/aws" 10 | "github.com/aws/aws-sdk-go/aws/session" 11 | "github.com/aws/aws-sdk-go/service/autoscaling" 12 | ) 13 | 14 | var asgClient *autoscaling.AutoScaling 15 | 16 | const ( 17 | EventASGTerminateDetailType = "EC2 Instance-terminate Lifecycle Action" 18 | EventEC2SpotInteruptionDetailType = "EC2 Spot Instance Interruption Warning" 19 | ) 20 | 21 | type ( 22 | ASGLifecycleEventDetail struct { 23 | LifecycleActionToken string 24 | AutoScalingGroupName string 25 | LifecycleHookName string 26 | EC2InstanceID string 27 | LifecycleTransition string 28 | } 29 | EC2SpotInterruptionEventDetail struct { 30 | InstanceID string `json:"instance-id"` 31 | InstanceAction string `json:"instance-action"` 32 | } 33 | ) 34 | 35 | func HandleRequest(ctx context.Context, event *events.CloudWatchEvent) error { 36 | printJSON("CloudWatch Event", event) 37 | 38 | var instanceToDrain string 39 | var finalAction = func() error { return nil } 40 | 41 | switch event.DetailType { 42 | case EventASGTerminateDetailType: 43 | asgEvent := &ASGLifecycleEventDetail{} 44 | if err := json.Unmarshal(event.Detail, &asgEvent); err != nil { 45 | return err 46 | } 47 | 48 | instanceToDrain = asgEvent.EC2InstanceID 49 | finalAction = asgEvent.CompleteLifecycle 50 | case EventEC2SpotInteruptionDetailType: 51 | spotEvent := &EC2SpotInterruptionEventDetail{} 52 | if err := json.Unmarshal(event.Detail, &spotEvent); err != nil { 53 | return err 54 | } 55 | 56 | instanceToDrain = spotEvent.InstanceID 57 | } 58 | 59 | // Getting instance UserData, because if ECS Instance was 60 | // created via CloudFormation, then ECS Cluster name 61 | // should be specified there in next format: 62 | // // #!/bin/bash -xe 63 | // // echo ECS_CLUSTER=${ECSCluster} >> /etc/ecs/ecs.config 64 | // // ... 65 | ecsCluster, err := GetClusterNameFromInstanceUserData(instanceToDrain) 66 | switch err { 67 | case nil: 68 | // do nothing 69 | case ErrMissingUserData: 70 | fmt.Printf("No UserData not found, instance %q probably not part of an ECS Cluster\n", instanceToDrain) 71 | case ErrInstanceTerminated: 72 | fmt.Printf("Instance %q already terminated", instanceToDrain) 73 | // if instance is already terminated, try compliting final action anyway 74 | // this is needed for the Spot instances particulary, see here: 75 | // https://docs.aws.amazon.com/en_us/autoscaling/ec2/userguide/lifecycle-hooks.html#lifecycle-hook-spot 76 | return finalAction() 77 | } 78 | 79 | fmt.Println("ECS Cluster -", ecsCluster) 80 | fmt.Println("EC2 Instance - ", instanceToDrain) 81 | 82 | // Doing actual "Drain" operation, which will move all the running 83 | // task from current instance to other aviliable instances. 84 | // This operation could take some time, so if we have a lot of task 85 | // on the instance, but 15 minutes lambda limit, should be enough 86 | if err := Drain(ecsCluster, instanceToDrain); err != nil { 87 | return err 88 | } 89 | 90 | // Do the final actions after the drain which is: 91 | // - Complete lifecycle action for ASG Hook 92 | // - Nothing for the Spot Interruption 93 | return finalAction() 94 | } 95 | 96 | func (asgEvent *ASGLifecycleEventDetail) CompleteLifecycle() error { 97 | // lazy init asgClient 98 | if asgClient == nil { 99 | asgClient = autoscaling.New(session.New()) 100 | } 101 | 102 | // TODO? 103 | // if the Drain fails, after timeout hook will be completed with ABANDON result, 104 | // which in case of instance termination will still Terminate the instance 105 | // https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html#lifecycle-hook-considerations 106 | // may be it worth to set Scale In protection on the instance, to complete the Drain manually? 107 | 108 | // Once instance drained, we can proceed with the termination 109 | if _, err := asgClient.CompleteLifecycleAction(&autoscaling.CompleteLifecycleActionInput{ 110 | InstanceId: &asgEvent.EC2InstanceID, 111 | LifecycleHookName: &asgEvent.LifecycleHookName, 112 | LifecycleActionToken: &asgEvent.LifecycleActionToken, 113 | AutoScalingGroupName: &asgEvent.AutoScalingGroupName, 114 | LifecycleActionResult: aws.String("CONTINUE"), 115 | }); err != nil { 116 | return err 117 | } 118 | 119 | fmt.Printf("Lifecycle hook action %q (%s) completed for ASG %q and InstanceID %q\n", 120 | asgEvent.LifecycleHookName, 121 | asgEvent.LifecycleActionToken, 122 | asgEvent.AutoScalingGroupName, 123 | asgEvent.EC2InstanceID) 124 | 125 | return nil 126 | } 127 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:base" 5 | ] 6 | } -------------------------------------------------------------------------------- /serverless.yml: -------------------------------------------------------------------------------- 1 | service: ecs-drain 2 | package: 3 | individually: true 4 | 5 | provider: 6 | name: aws 7 | runtime: provided.al2 8 | region: us-east-1 9 | memorySize: 128 10 | timeout: 900 11 | stage: prod 12 | logRetentionInDays: 14 13 | iamRoleStatements: 14 | - Effect: Allow 15 | Action: 16 | - autoscaling:CompleteLifecycleAction 17 | - ec2:DescribeInstanceAttribute 18 | - ec2:DescribeInstances 19 | - ecs:ListContainerInstances 20 | - ecs:SubmitContainerStateChange 21 | - ecs:DescribeContainerInstances 22 | - ecs:UpdateContainerInstancesState 23 | - ecs:ListTasks 24 | - ecs:DescribeTasks 25 | Resource: "*" 26 | 27 | functions: 28 | main: 29 | handler: bootstrap 30 | package: 31 | exclude: 32 | - ./** 33 | include: 34 | - ./bootstrap 35 | events: 36 | - cloudwatchEvent: 37 | event: 38 | source: 39 | - "aws.autoscaling" 40 | detail-type: 41 | - "EC2 Instance-terminate Lifecycle Action" 42 | - cloudwatchEvent: 43 | event: 44 | source: 45 | - "aws.ec2" 46 | detail-type: 47 | - "EC2 Spot Instance Interruption Warning" 48 | 49 | resources: 50 | Description: | 51 | Lambda for automatization of ECS Instances operations: https://github.com/getsocial-rnd/ecs-drain-lambda 52 | --------------------------------------------------------------------------------