Symptom
A scale-out happened, but new instances never join the load balancer. Or a scale-in is stuck, the old instances keep running, and an instance refresh or deployment sits there waiting. describe-auto-scaling-groups shows instances in Pending:Wait or Terminating:Wait. Warm pool instances can show Warmed:Pending:Wait.
A lifecycle hook pauses the instance until something calls CompleteLifecycleAction or the heartbeat timeout runs out. If the handler is broken, every instance waits out the full timeout, which defaults to one hour. If the handler keeps sending heartbeats without finishing, an instance can wait far longer.
1. Find the stuck instances and the hook
ASG=web-prod-asg
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names $ASG \
--query 'AutoScalingGroups[0].Instances[?contains(LifecycleState, `Wait`)].[InstanceId,LifecycleState,AvailabilityZone]' \
--output table
aws autoscaling describe-lifecycle-hooks --auto-scaling-group-name $ASG \
--query 'LifecycleHooks[].[LifecycleHookName,LifecycleTransition,HeartbeatTimeout,GlobalTimeout,DefaultResult,NotificationTargetARN]' \
--output table
aws autoscaling describe-scaling-activities --auto-scaling-group-name $ASG --max-items 10 \
--query 'Activities[].[StartTime,StatusCode,Description,StatusMessage]' --output table
Write down three things for each hook:
LifecycleTransition:autoscaling:EC2_INSTANCE_LAUNCHINGorautoscaling:EC2_INSTANCE_TERMINATING.HeartbeatTimeout: in seconds, 30 to 7200. The default is 3600.DefaultResult:CONTINUEorABANDON. This is what happens when the timeout runs out.
GlobalTimeout caps the total wait at 48 hours or 100 times the heartbeat timeout, whichever is smaller.
2. Work out why nobody completed it
| What you find | Likely cause | Check |
|---|---|---|
No NotificationTargetARN and no EventBridge rule | The hook was created and nothing listens to it | aws events list-rules. Look for a rule on the lifecycle action event |
| EventBridge rule exists, target Lambda shows errors | The handler is failing | Lambda Errors metric and the function's log group |
| Lambda succeeds but the instance still waits | The handler doesn't call complete-lifecycle-action, or calls it for the wrong hook or ASG name | Look for the call in CloudTrail |
Handler gets AccessDenied | Its role can't call autoscaling:CompleteLifecycleAction | Lambda logs, IAM policy |
| Script on the instance finishes the hook, launch hook still waits | User data or bootstrap failed before the final call | /var/log/cloud-init-output.log over SSM |
| SNS or SQS target, nothing processed | Queue consumer is down, or the queue policy or KMS key rejects Auto Scaling | Queue depth, the role in RoleARN on the hook |
| Instance waits for hours, then finally moves on | The handler sends heartbeats but never finishes | RecordLifecycleActionHeartbeat events in CloudTrail |
Confirm in CloudTrail whether anything called the API:
for EV in CompleteLifecycleAction RecordLifecycleActionHeartbeat; do
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=$EV \
--start-time $(date -u -d '-6 hours' +%FT%TZ) \
--query 'Events[].[EventTime,Username,EventName]' --output table
done
The EventBridge event types are EC2 Instance-launch Lifecycle Action and EC2 Instance-terminate Lifecycle Action, with source aws.autoscaling. A rule that matches the wait-state events must use those exact detail-type values:
{
"source": ["aws.autoscaling"],
"detail-type": ["EC2 Instance-terminate Lifecycle Action"],
"detail": { "AutoScalingGroupName": ["web-prod-asg"] }
}
Check what the rule actually matches and whether invocations fail:
aws events list-rules --query "Rules[?contains(EventPattern, 'Lifecycle Action')].[Name,State,EventPattern]" --output table
aws cloudwatch get-metric-statistics --namespace AWS/Events --metric-name FailedInvocations \
--dimensions Name=RuleName,Value=asg-terminate-hook --statistics Sum --period 300 \
--start-time $(date -u -d '-3 hours' +%FT%TZ) --end-time $(date -u +%FT%TZ)
3. Release the instances
Before you release anything, decide what each result does:
| Transition | CONTINUE | ABANDON |
|---|---|---|
| Launch | The instance goes InService and is registered with the load balancer | The instance is terminated and Auto Scaling launches a replacement |
| Terminate | The instance is terminated | The instance is terminated, and any other termination hooks are skipped |
Warning
CONTINUEon a launch hook puts the instance into service and into the target group, even though the bootstrap may never have finished. If health checks are shallow, users can hit a half-configured instance. When you're not sure the bootstrap worked, useABANDONand let Auto Scaling launch a fresh instance.
Complete the action for one instance:
aws autoscaling complete-lifecycle-action \
--auto-scaling-group-name $ASG \
--lifecycle-hook-name drain-on-terminate \
--instance-id i-0abc1234def567890 \
--lifecycle-action-result CONTINUE
Release every instance waiting on a terminate hook:
HOOK=drain-on-terminate
for ID in $(aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names $ASG \
--query 'AutoScalingGroups[0].Instances[?LifecycleState==`Terminating:Wait`].InstanceId' --output text); do
echo "Completing $ID"
aws autoscaling complete-lifecycle-action --auto-scaling-group-name $ASG \
--lifecycle-hook-name $HOOK --instance-id $ID --lifecycle-action-result CONTINUE
done
Caution
A terminate hook usually exists to drain connections, flush logs, deregister from a cluster or take a final backup. If you release it by hand, that work is skipped. Do it yourself first. For example, run the drain script over SSM Run Command, or copy the logs off, and then complete the action.
If the handler is slow rather than broken, extend the wait instead of cutting it short:
aws autoscaling record-lifecycle-action-heartbeat --auto-scaling-group-name $ASG \
--lifecycle-hook-name $HOOK --instance-id i-0abc1234def567890
Each heartbeat adds one more HeartbeatTimeout to the wait, up to the global timeout.
If the hook should never have existed, delete it. Instances already waiting stay in the wait state until you complete them or the timeout runs out:
aws autoscaling delete-lifecycle-hook --auto-scaling-group-name $ASG --lifecycle-hook-name $HOOK
4. Fix the handler
For a Lambda behind an EventBridge rule, this is the minimum you need:
- An execution role allowed to call
autoscaling:CompleteLifecycleActionandautoscaling:RecordLifecycleActionHeartbeat. Scope it to the ASG ARN. - Code that calls
CompleteLifecycleActionon every path, including failures. ReadLifecycleHookName,AutoScalingGroupName,EC2InstanceIdandLifecycleActionTokenfromevent["detail"].
import boto3
asg = boto3.client("autoscaling")
def handler(event, context):
d = event["detail"]
result = "CONTINUE"
try:
drain(d["EC2InstanceId"]) # your work: SSM command, deregister, flush
except Exception as exc:
print(f"drain failed for {d['EC2InstanceId']}: {exc}")
result = "ABANDON" # still finish the hook; don't leave it waiting
asg.complete_lifecycle_action(
AutoScalingGroupName=d["AutoScalingGroupName"],
LifecycleHookName=d["LifecycleHookName"],
LifecycleActionToken=d["LifecycleActionToken"],
LifecycleActionResult=result,
)
Set the Lambda timeout below the hook's HeartbeatTimeout. If the work can run longer than that, send heartbeats while it runs.
For a launch hook completed from user data, make the call the last step of bootstrap, after your own health check passes. The instance profile then needs autoscaling:CompleteLifecycleAction. Use IMDSv2 to get the instance ID.
Prevent it next time
- Set the timeout to fit the work. Base
HeartbeatTimeouton how long the work really takes, not the one-hour default. A five-minute drain doesn't need a one-hour hook. - Choose
DefaultResultdeliberately. For launch hooks,ABANDONis safer: a failed bootstrap gets a fresh instance instead of serving traffic. For terminate hooks,CONTINUEmeans the instance is always removed in the end. - Alarm on waiting instances. Alarm on handler
Errors, on EventBridgeFailedInvocations, and on instances that stay in a wait state longer than expected. For the last one, use a scheduled check that runs thedescribe-auto-scaling-groupsquery above. - Exercise the hook regularly. Scale out and in by one instance in staging after every handler or IAM change. A hook that only runs during real scale events breaks without anyone noticing.
- Account for hooks in deployments. Instance refresh and blue/green deployments wait on lifecycle hooks too. Include the hook time in your deployment timeouts.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get