Created
September 1, 2020 16:56
-
-
Save johnstanfield/71b41444482746235346b3cf5a54cbe3 to your computer and use it in GitHub Desktop.
terminate ECS instances in an auto-scaling group
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# inspects EC2 instances in an ECS cluster and terminates instances that are in a DRAINING state | |
# the instances are terminated via autoscaling, and the desired capacity is decremented | |
# | |
# this is the proper way to terminate EC2 instances in an ECS cluster because: | |
# - if you just decrement the desired capacity, instances with running tasks may be terminated, and you may have an outage | |
# - if you terminate instances with zero tasks, the autoscaling group will just replace them | |
# | |
# USAGE | |
# DRY RUN | |
# terminate-draining-instances my-cluster | |
# FOR REAL | |
# terminate-draining-instances my-cluster -y | |
arns=$(aws ecs list-container-instances --cluster $1 --status DRAINING | jq '[.containerInstanceArns[]] | join(" ")' -j) | |
if [ "$2" = "-y" ]; then | |
for instanceid in `aws ecs describe-container-instances --cluster $1 --container-instances $arns | jq '.containerInstances[].ec2InstanceId' --raw-output`; do | |
echo terminating $instanceid | |
aws autoscaling terminate-instance-in-auto-scaling-group --instance-id $instanceid --should-decrement-desired-capacity | |
done | |
else | |
echo these instances will be terminated: | |
aws ecs describe-container-instances --cluster $1 --container-instances $arns | jq '.containerInstances[].ec2InstanceId' --raw-output | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment