CodeDeploy for EC2 and On-Premises
Overview
AWS CodeDeploy automates application deployments to EC2 instances, on-premises servers, Lambda functions and ECS services. For EC2 and on-premises it uses an agent on each server that downloads a revision (from S3 or GitHub) and follows instructions in an appspec.yml file.
Imagine replacing the engines on a fleet of buses while they are still carrying passengers. In-place deployment swaps engines bus by bus in the depot; blue/green brings in a whole new fleet, moves passengers across and only then retires the old buses. CodeDeploy lets you choose either, with health checks and rollbacks.
The exam asks you to pick between in-place and blue/green, choose a deployment configuration, order the lifecycle hooks and configure automatic rollback on failure or CloudWatch alarm.
Key Concepts
- Application contains deployment groups (set of instances by tag, ASG or both) and revisions (S3 or GitHub bundle with appspec.yml).
- In-place: stop the app, install the new revision on existing instances, in batches. Instances are deregistered from the load balancer during their batch.
- Blue/green (EC2): provisions a replacement ASG or copies it, installs the revision, then shifts load balancer traffic; originals can be kept or terminated after a wait.
- Built-in configs: CodeDeployDefault.AllAtOnce, HalfAtATime, OneAtATime, and custom minimum-healthy-hosts settings.
- Hook order (in-place): ApplicationStop, DownloadBundle, BeforeInstall, Install, AfterInstall, ApplicationStart, ValidateService.
- Automatic rollback on deployment failure or when a CloudWatch alarm fires; rollback redeploys the last successful revision as a new deployment.
- The agent needs an instance profile with S3 read access; install it via Systems Manager State Manager for automation.
- Scale-out during deployment: new ASG instances receive the last successful revision automatically; a revision mismatch can occur if a deployment fails mid-way.
Detailed Notes
appspec.yml for EC2
version: 0.0
os: linux
files:
- source: /build/app
destination: /opt/orders
permissions:
- object: /opt/orders
owner: appuser
mode: 755
hooks:
ApplicationStop:
- location: scripts/stop.sh
timeout: 60
BeforeInstall:
- location: scripts/backup.sh
AfterInstall:
- location: scripts/configure.sh
ApplicationStart:
- location: scripts/start.sh
ValidateService:
- location: scripts/smoke.sh
timeout: 120
A non-zero exit code from any script fails that hook and the deployment (instance fails). ApplicationStop uses the script from the previously successful revision, which is a classic gotcha when the old script is broken.
Full lifecycle with a load balancer
| Hook | In-place | Blue/green (replacement) |
|---|---|---|
| BeforeBlockTraffic / BlockTraffic / AfterBlockTraffic | Run on the instance being updated | Run on original instances |
| ApplicationStop ... ValidateService | Run on the instance being updated | Run on replacement instances |
| BeforeAllowTraffic / AllowTraffic / AfterAllowTraffic | Re-register the instance | Register replacement instances |
The AllowTraffic and BlockTraffic steps are performed by CodeDeploy and cannot be scripted.
Deployment configurations
| Configuration | Behaviour |
|---|---|
| AllAtOnce | All instances in one batch; fastest, riskiest |
| HalfAtATime | 50% at a time; needs at least half healthy |
| OneAtATime | One instance at a time; safest, slowest. Succeeds if all but the last succeed |
| Custom | minimumHealthyHosts count or percentage |
Blue/green on EC2
CodeDeploy can create a new Auto Scaling group by copying the current one, deploy to it, reroute the load balancer (target group registration) and terminate the original after a configurable wait, or keep it. Requires a load balancer (Classic, ALB or NLB). Rollback is near-instant because the original capacity is still running during the wait.
Triggering and rollback
aws deploy create-deployment \
--application-name orders --deployment-group-name prod \
--s3-location bucket=artifacts,key=orders-1.4.zip,bundleType=zip \
--auto-rollback-configuration enabled=true,events=DEPLOYMENT_FAILURE,DEPLOYMENT_STOP_ON_ALARM \
--deployment-config-name CodeDeployDefault.OneAtATime
Alarm integration: attach CloudWatch alarms (for example ALB 5xx rate) to the deployment group. If an alarm enters ALARM during deployment, CodeDeploy stops it and, if configured, rolls back.
ASG integration
When a deployment group is tied to an ASG, CodeDeploy installs a lifecycle hook (CodeDeploy-managed-automatic-launch-deployment-hook) so new instances are held in Pending:Wait until the revision is deployed. If deployment fails, the instance is terminated and replaced. During blue/green, scale-in/out events are suspended appropriately.
Troubleshooting
- Agent log:
/var/log/aws/codedeploy-agent/codedeploy-agent.log; script output:/opt/codedeploy-agent/deployment-root/<id>/logs/scripts.log. - No instances found: tag mismatch or agent not running.
- AccessDenied to S3: missing instance profile permissions.
- Deployment hangs at a hook: script waiting for input; set timeouts.
- Overall deployment fails with HEALTH_CONSTRAINTS: fewer healthy hosts than the minimum.
On-premises
Register each server (IAM user or, preferably, IAM session via register-on-premises-instance with an IAM role), install the agent and tag. Everything else works the same.
Deployment groups and tags
A deployment group can combine tag groups (AND across groups, OR within), ASG names, or both. Use one group per environment, and deploy the same revision to each group in order.
Agent, permissions and failure analysis
The CodeDeploy agent must run on every EC2 or on-premises instance. Install and update it with a Systems Manager State Manager association (package AWSCodeDeployAgent) so new instances in an Auto Scaling group are covered. Two roles are involved: the service role (CodeDeploy reads instance and ASG details, can use AWSCodeDeployRole) and the instance profile (the agent reads the revision from S3 and the deployment artifacts). On-premises servers register with aws deploy register-on-premises-instance and an IAM user or role.
| Symptom | Likely cause | Where to look |
|---|---|---|
| Deployment stuck at the first event | Agent not running or no connectivity to the CodeDeploy endpoint | /var/log/aws/codedeploy-agent/codedeploy-agent.log |
| Script failed in a lifecycle hook | Non-zero exit code or timeout | /opt/codedeploy-agent/deployment-root/<id>/logs/scripts.log |
| Revision cannot be downloaded | Instance profile lacks S3 or KMS permission | CodeDeploy console error and CloudTrail |
| ApplicationStop fails on first deploy | Hook runs from the previously deployed revision | Use --ignore-application-stop-failures or fix the script |
| Instances not selected | Tag or ASG filter mismatch | Deployment group configuration |
Mutable deployments (in-place) change running servers and are quick but risk configuration drift; immutable approaches (blue/green, new AMI) replace servers and make rollback simple at the cost of extra capacity and a longer rollout.
Real World Example
Scenario: a travel site has 40 EC2 web servers behind an ALB. Deployments used to run through SSH scripts and occasionally left half the fleet on the old version. They adopt CodeDeploy with an ASG-based deployment group and OneAtATime in staging, HalfAtATime in production.
ValidateService calls a health endpoint, and an alarm on the ALB's 5XX count is attached with auto-rollback. When a bad configuration file causes errors, the alarm trips after the first batch, CodeDeploy stops and re-deploys the previous revision, and only a fraction of users saw errors for a few minutes.
Architecture Diagram
Instances leave the load balancer one batch at a time while hooks run.
- 1A revision is uploaded to S3 and a deployment is created for the group.
- 2The agent on an instance in the first batch is deregistered from the load balancer.
- 3Hooks run: stop, install, configure, start and validate.
- 4The instance is registered again and the next batch begins.
- 5If a deployment fails or an alarm fires, the last good revision is redeployed.
Best Practices
- ✓Prefer blue/green where fast rollback and zero reduced capacity matter; use in-place for cost-sensitive fleets.
- ✓Always include a ValidateService hook with real health checks and sensible timeouts.
- ✓Attach CloudWatch alarms and enable automatic rollback.
- ✓Keep hook scripts idempotent; they may re-run during rollback.
- ✓Install and update the agent through Systems Manager to avoid drift.
Common Interview Questions
Exam Tips
DOP-C02 focus
- "Fastest rollback with no capacity reduction" = blue/green.
- "Validate the app before traffic returns" = ValidateService (or BeforeAllowTraffic) hook.
- New ASG instances automatically get the last successful revision.
- "Roll back if error rate rises" = CloudWatch alarm on the deployment group.
Finished this lesson?
0 of 44 lessons done · 0% of the course

