Home / AWS

AWSRunbookIntermediate

EC2 Auto Scaling instances stuck in Pending:Wait or Terminating:Wait: a lifecycle hook runbook

Instances sit in Pending:Wait or Terminating:Wait and scaling stalls. Find the hook, see why nobody completed it, release the instances safely and make the hook handler reliable.

Deepak Bhardwaj6 min read

Applies toAmazon EC2 Auto Scaling lifecycle hooks (launch and termination, including warm pools), AWS CLI v2, EventBridge, SNS and SQS notification targets

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_LAUNCHING or autoscaling:EC2_INSTANCE_TERMINATING.
  • HeartbeatTimeout: in seconds, 30 to 7200. The default is 3600.
  • DefaultResult: CONTINUE or ABANDON. 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

CONTINUE on 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, use ABANDON and 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:CompleteLifecycleAction and autoscaling:RecordLifecycleActionHeartbeat. Scope it to the ASG ARN.
  • Code that calls CompleteLifecycleAction on every path, including failures. Read LifecycleHookName, AutoScalingGroupName, EC2InstanceId and LifecycleActionToken from event["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 HeartbeatTimeout on how long the work really takes, not the one-hour default. A five-minute drain doesn't need a one-hour hook.
  • Choose DefaultResult deliberately. For launch hooks, ABANDON is safer: a failed bootstrap gets a fresh instance instead of serving traffic. For terminate hooks, CONTINUE means the instance is always removed in the end.
  • Alarm on waiting instances. Alarm on handler Errors, on EventBridge FailedInvocations, and on instances that stay in a wait state longer than expected. For the last one, use a scheduled check that runs the describe-auto-scaling-groups query 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.