Sub topic 17
Lifecycle hooks and instance refresh for safe changes
This chapter assumes you can create an Auto Scaling group with a launch template and attach it to a target group. It also assumes you know how health checks and the deregistration delay work. Here you will learn how to pause an instance during launch or termination, and how to replace every instance in a group without dropping traffic.
Why scaling needs safe change points
By default, an Auto Scaling group acts on instances without waiting for your software. A new instance goes into service as soon as it boots, and a terminating instance is shut down right after it leaves the load balancer. That is risky when an instance must finish setup, ship logs, or hand off work first. Two features address this:
- Lifecycle hooks pause an instance at a launch or termination transition so your code can run.
- Instance refresh replaces instances in batches when you change the launch template.
Lifecycle hooks
A lifecycle hook holds an instance in a wait state until your code reports completion or a timeout expires. There are two transitions you can hook:
autoscaling:EC2_INSTANCE_LAUNCHINGholds the instance inPending:Wait.autoscaling:EC2_INSTANCE_TERMINATINGholds it inTerminating:Wait.
What happens during each wait
During Pending:Wait, the instance is not yet registered with the target group, and the health check grace period has not started. Use this window to install software, pull configuration, or warm caches. When the hook completes, the group registers the instance and starts the grace period.
During Terminating:Wait, the group deregisters the instance from the target group. The deregistration delay runs while the hook waits, so in-flight requests can finish. Use this window to upload logs, flush queues, or finish jobs.
Timeouts and results
The heartbeat timeout defaults to 3600 seconds and can be set from 30 to 7200. If nobody completes the action before the timeout, the default result applies:
CONTINUElets the transition proceed.ABANDONterminates a launching instance. On a terminating instance, it also lets termination proceed.
You can extend a wait by recording a heartbeat. The total wait cannot exceed 48 hours or 100 times the heartbeat timeout, whichever is smaller.
Creating a hook and completing it
Lifecycle events are published to Amazon EventBridge. You can also add an SNS topic or SQS queue as a notification target. Create a terminate hook like this:
aws autoscaling put-lifecycle-hook \
--auto-scaling-group-name web-asg \
--lifecycle-hook-name drain-before-terminate \
--lifecycle-transition autoscaling:EC2_INSTANCE_TERMINATING \
--heartbeat-timeout 300 \
--default-result CONTINUEYour handler might be a script on the instance, a Lambda function, or an SSM Automation runbook. When it finishes, it must signal completion:
aws autoscaling complete-lifecycle-action \
--auto-scaling-group-name web-asg \
--lifecycle-hook-name drain-before-terminate \
--instance-id i-0123456789abcdef0 \
--lifecycle-action-result CONTINUETo buy more time, call record-lifecycle-action-heartbeat with the same group, hook and instance arguments.
Instance refresh
Changing a launch template does not touch running instances. Only new instances use the new version. An instance refresh replaces existing instances gradually, so you can roll out a new AMI or configuration.
First point the group at the new template version, then start the refresh:
aws autoscaling update-auto-scaling-group \
--auto-scaling-group-name web-asg \
--launch-template LaunchTemplateName=web-lt,Version='$Latest'
aws autoscaling start-instance-refresh \
--auto-scaling-group-name web-asg \
--preferences '{"MinHealthyPercentage":90,"InstanceWarmup":300,"AutoRollback":true}'Key preferences
| Preference | Effect |
|---|---|
| `MinHealthyPercentage` | Share of desired capacity that must stay healthy. The default is 90. |
| `MaxHealthyPercentage` | Allows capacity to exceed desired during the refresh, up to 200, so new instances launch before old ones terminate. |
| `InstanceWarmup` | Seconds a new instance must run before it counts as healthy. If omitted, the health check grace period is used. |
| `AutoRollback` | Returns the group to its previous configuration if the refresh fails. |
| `CheckpointPercentages` | Pauses at set percentages so you can verify the new instances. |
| `SkipMatching` | Skips instances that already match the desired configuration. |
| `ScaleInProtectedInstances` | Controls whether instances with scale-in protection are replaced. |
With a small group, a 90 percent minimum means replacing one instance at a time, because the group cannot drop below the minimum. Ten instances at 90 percent also replace one instance per batch. A lower percentage is faster but reduces spare capacity during the rollout.
Terminate lifecycle hooks still run for each replaced instance. A refresh therefore drains connections and completes your cleanup logic. A slow hook slows the whole refresh.
Monitoring and stopping
aws autoscaling describe-instance-refreshes \
--auto-scaling-group-name web-asg
aws autoscaling cancel-instance-refresh \
--auto-scaling-group-name web-asgCancelling stops further replacements but does not undo ones already done. To return to the previous configuration, use rollback-instance-refresh.
Common errors
- The hook never completes. Your handler lacks permission for
autoscaling:CompleteLifecycleAction, or it used the wrong hook name or instance ID. The instance sits in the wait state until the timeout. - A refresh stalls near the start. New instances fail the target group health check, so the group never sees enough healthy capacity. Check the health check path and the security groups first.
- Nothing changes after a refresh. The group still points at an old template version. Use
$Latestor$Defaultdeliberately, and confirm the version number. - A refresh runs too fast. A short
InstanceWarmuplets batches proceed before the application is ready.
Exercise
A terminate lifecycle hook has a 300-second heartbeat timeout and a default result of CONTINUE. Your cleanup script takes 400 seconds and does not send a heartbeat. What happens, and how do you fix it?
Show answer
At 300 seconds the hook times out and the default result CONTINUE applies, so the instance terminates while the script is still running and cleanup is cut off. Fix it by sending record-lifecycle-action-heartbeat before the timeout, or by raising the heartbeat timeout above the worst-case script time (for example 600 seconds). The script should call complete-lifecycle-action when it finishes.
Exercise
You run a refresh on a group with 10 instances and MinHealthyPercentage set to 100. How can you let it make progress without lowering availability?
Show answer
Set MaxHealthyPercentage above 100, for example 110. The group can then launch a new instance before terminating an old one, so healthy capacity never falls below desired.