An efficient way to terminate and shrink an Autoscaling Group (AWS)
Originally published in The Spinnaker Community Blog on Medium.
The following pattern is suitable for scenarios where you would like to terminate more than one instance in an autoscaling group (ASG) with a matching decrement to desired capacity.
While the AWS SDK does support terminating a single instance in an ASG with a capacity adjustment, it offers nothing when it comes to multiple instance terminations.
terminate-instance-in-auto-scaling-group - AWS CLI 1.11.51 Command Reference
It’s worth noting that the autoscaler will behave inconsistently should you attempt to call terminate-instance-in-auto-scaling-group in parallel.
This should be avoided.
The Pattern
Tag the instances pending termination
- A tag to denote the ASG name that the instance is currently associated with (spinnaker:Detached).
- A tag to denote that the instance is pending termination (spinnaker:PendingTermination).
Detach the instances from the autoscaling group
The AWS SDK supports detaching multiple instances from an ASG with an equivalent decrease in desired capacity.
At this point you have a correctly sized ASG that does not contain the instances pending termination.
Terminate instances
Terminate all instances with the spinnaker:PendingTermination tag.
For safety (and because things can go wrong) I would suggest having a periodic background process that looks for any tagged instance and terminates if it is not associated with an ASG.
Conclusion
This pattern is implemented with Spinnaker (see DetachInstancesAtomicOperation) and has been successfully used by a number of our users.
It’s particularly relevant to teams that have long running jobs and need additional control over how their ASGs should scale down.