Home / AWS

AWSTroubleshootingIntermediate

CodeDeploy EC2 deployment failed: agent not responding, ScriptFailed and lifecycle hook timeouts

A CodeDeploy deployment to EC2 fails or hangs. Find the failed instance and lifecycle event, read the script log tail, fix agent, IAM, AppSpec and file-exists problems, and turn on auto rollback.

Deepak Bhardwaj7 min read

Applies toAWS CodeDeploy (EC2/On-premises compute platform, in-place deployments), CodeDeploy agent on Amazon Linux 2023, Ubuntu and Windows Server, AWS CLI v2

Symptom

Your pipeline reports that a CodeDeploy deployment failed, or it sits in InProgress until it times out. The console usually shows one of these messages:

  • "The overall deployment failed because too many individual instances failed deployment"
  • "The deployment failed because no instances were found for your deployment group"
  • "The deployment failed because a specified file already exists at this location"
  • A lifecycle event stuck in Pending for an hour

The deployment-level message rarely gives the cause. Work down from the deployment to the instance, then to the lifecycle event, then to the log on the box.

Step 1: find the failed deployment and the failed instances

APP=web-app
DG=prod-web

# Most recent failed deployments for the group
aws deploy list-deployments --application-name "$APP" \
  --deployment-group-name "$DG" --include-only-statuses Failed Stopped \
  --query 'deployments[:5]' --output text

DEP=d-ABCDEFGHI

# Overall status and error
aws deploy get-deployment --deployment-id "$DEP" \
  --query 'deploymentInfo.{status:status, error:errorInformation, overview:deploymentOverview, config:deploymentConfigName}'

# Which instances failed
aws deploy list-deployment-targets --deployment-id "$DEP" \
  --target-filters TargetStatus=Failed

Step 2: read the lifecycle event diagnostics

For each failed target, CodeDeploy records which lifecycle event failed, the script name and up to the last 4 KB of its log.

aws deploy get-deployment-target --deployment-id "$DEP" --target-id i-0abc123def4567890 \
  --query 'deploymentTarget.instanceTarget.lifecycleEvents[?status!=`Succeeded`].{event:lifecycleEventName, status:status, code:diagnostics.errorCode, script:diagnostics.scriptName, msg:diagnostics.message, tail:diagnostics.logTail}'

The errorCode tells you which kind of problem you have:

errorCode Meaning Usual fix
ScriptFailed The hook script exited with a non-zero code Read logTail. Fix the script or the service it starts
ScriptTimedOut The script ran past its timeout in the AppSpec Increase timeout (maximum 3600 seconds), or stop the script blocking on a foreground process
ScriptMissing The path in appspec.yml is not in the bundle Check the path is relative to the bundle root and that the case matches
ScriptNotExecutable The file is not a recognised executable Add a shebang line, chmod +x before you bundle, use LF line endings
UnknownError The agent could not run the script Check the agent log (Step 4)
Event Pending, no diagnostics The agent never picked up the event Agent, IAM or network problem (Step 3)

Tip

A script that starts a daemon in the foreground (for example java -jar app.jar with no & or systemd) makes the hook run until timeout and then fail as ScriptTimedOut. Start long-running processes through systemctl start and have the hook return.

Step 3: lifecycle events stuck in Pending

If the first event (ApplicationStop or DownloadBundle) never starts, CodeDeploy can't talk to the agent on the instance.

Check the agent on the instance, for example through Session Manager:

# Linux
sudo systemctl status codedeploy-agent
sudo tail -n 100 /var/log/aws/codedeploy-agent/codedeploy-agent.log
# Windows
Get-Service codedeployagent
Get-Content 'C:\ProgramData\Amazon\CodeDeploy\log\codedeploy-agent-log.txt' -Tail 100

If the agent is missing or outdated, install it across the fleet with the SSM Distributor package:

aws ssm send-command --document-name AWS-ConfigureAWSPackage \
  --targets Key=tag:CodeDeployGroup,Values=prod-web \
  --parameters '{"action":["Install"],"name":["AWSCodeDeployAgent"]}' \
  --max-concurrency 25% --max-errors 1

Go through these causes in order:

Check What to look for
Instance profile The instance has an IAM role. It can read the revision bucket (s3:GetObject, plus kms:Decrypt if the bucket uses SSE-KMS)
Network The instance can reach CodeDeploy and S3, either through NAT or through VPC endpoints (com.amazonaws.<region>.codedeploy, com.amazonaws.<region>.codedeploy-commands-secure and an S3 gateway endpoint)
Agent log AccessDenied when polling, credential errors, or proxy errors
Clock Severe clock skew breaks SigV4 signing. Check chronyc tracking
Agent started before the role If you attached the role after boot, restart the agent: sudo systemctl restart codedeploy-agent

Step 4: read the full script log on the instance

The 4 KB tail is often not enough. On Linux, each deployment has its own log:

sudo ls /opt/codedeploy-agent/deployment-root/
# <deployment-group-id>/<deployment-id>/logs/scripts.log
sudo cat /opt/codedeploy-agent/deployment-root/*/"$DEP"/logs/scripts.log

# Combined log across deployments
sudo tail -n 200 /opt/codedeploy-agent/deployment-root/deployment-logs/codedeploy-agent-deployments.log

On Windows the same structure is under C:\ProgramData\Amazon\CodeDeploy\.

Common failure patterns

"No instances found for your deployment group"

The deployment group matches nothing. Compare its tag filters or Auto Scaling groups with the real instances:

aws deploy get-deployment-group --application-name "$APP" --deployment-group-name "$DG" \
  --query 'deploymentGroupInfo.{ec2Tags:ec2TagFilters, tagSet:ec2TagSet, asgs:autoScalingGroups[].name}'

Tag keys and values are case-sensitive. Stopped instances are not deployment targets.

ApplicationStop fails on every deployment

ApplicationStop runs the script from the previous successful revision, so fixing the script in your new bundle does not help. Redeploy once and skip that hook's failure:

aws deploy create-deployment --application-name "$APP" --deployment-group-name "$DG" \
  --s3-location bucket=my-artifacts,key=web-app/build-412.zip,bundleType=zip \
  --ignore-application-stop-failures

When the new revision succeeds, its ApplicationStop script is the one used next time.

"A specified file already exists at this location"

Files that are already in the destination folder but were not installed by the last CodeDeploy revision block the Install event. Set the behaviour in appspec.yml:

version: 0.0
os: linux
files:
  - source: /
    destination: /opt/web-app
file_exists_behavior: OVERWRITE   # DISALLOW (default) | OVERWRITE | RETAIN
hooks:
  ApplicationStart:
    - location: scripts/start.sh
      timeout: 300
      runas: root
  ValidateService:
    - location: scripts/health.sh
      timeout: 120

You can also pass --file-exists-behavior OVERWRITE to create-deployment.

Warning

OVERWRITE replaces whatever is at the destination, including config files someone edited by hand on the instance. Move environment-specific config to Parameter Store or Secrets Manager before you turn it on.

Instance fails BlockTraffic or AllowTraffic

With a load balancer configured, CodeDeploy deregisters each instance before the deployment and registers it again afterwards. Long waits here come from the target group's deregistration delay and health check settings, not from your scripts. A failed AllowTraffic usually means the instance never passed the target group health check after ValidateService succeeded. Make ValidateService call the same health check path the load balancer uses.

Disk full on the instance

The agent keeps old revisions under deployment-root. Lower :max_revisions: in /etc/codedeploy-agent/conf/codedeployagent.yml (Windows: conf.yml under C:\ProgramData\Amazon\CodeDeploy\) and restart the agent.

Stop a bad deployment and roll back

# Stop now and roll back instances already updated
aws deploy stop-deployment --deployment-id "$DEP" --auto-rollback-enabled

A rollback is a new deployment of the last good revision. It runs the same hooks, so it fails too if the cause is the agent or IAM rather than the code.

Prevent it next time

Turn on automatic rollback on failure and on alarm:

aws deploy update-deployment-group --application-name "$APP" \
  --current-deployment-group-name "$DG" \
  --auto-rollback-configuration '{"enabled":true,"events":["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM"]}' \
  --alarm-configuration '{"enabled":true,"alarms":[{"name":"web-5xx-high"}]}'
  • Use a deployment configuration such as CodeDeployDefault.HalfAtATime or a custom minimum healthy hosts value, so one bad revision can't take down the whole fleet.
  • Bake the CodeDeploy agent into your AMI, or keep it current with an SSM State Manager association that runs AWS-ConfigureAWSPackage.
  • Make every hook script idempotent, give it a realistic timeout, and have it exit non-zero with a clear message when it fails.
  • Run ValidateService against the real health endpoint so bad builds fail before traffic returns.