AWS CodeDeploy
Core concept: CodeDeploy automates application deployments to EC2, Lambda, and ECS with traffic shifting, rollback, and lifecycle hooks.
๐ฐ What Is CodeDeploy?โ
CodeDeploy is like a smart deployment manager. Instead of manually updating your servers one by one, CodeDeploy orchestrates the rollout โ shifting traffic gradually, running health checks, and automatically rolling back if something goes wrong.
Deployment Targetsโ
| Platform | Deployment Type | Agent | Traffic Control |
|---|---|---|---|
| EC2/On-Premises | In-place or Blue/Green | โ CodeDeploy Agent | ASG, tags |
| Lambda | Traffic shifting (aliases) | โ Not needed | Alias routing |
| ECS | Blue/Green (ALB) | โ Not needed | Target group swap |
Deployment Strategiesโ
EC2 Deployment Strategiesโ
| Strategy | Description | Downtime |
|---|---|---|
| AllAtOnce | Deploy to all instances simultaneously | โ ๏ธ Brief |
| HalfAtATime | Deploy to 50% of instances, then remaining | Minimal |
| OneAtATime | Deploy to one instance at a time | None |
| Blue/Green | Create new ASG, shift ALB traffic | None |
Lambda Deployment Configurationsโ
| Configuration | Behavior |
|---|---|
| LambdaAllAtOnce | Shift 100% traffic immediately |
| LambdaCanary10Percent5Minutes | 10% โ wait 5 min โ 90% |
| LambdaCanary10Percent10Minutes | 10% โ wait 10 min โ 90% |
| LambdaCanary10Percent15Minutes | 10% โ wait 15 min โ 90% |
| LambdaCanary10Percent30Minutes | 10% โ wait 30 min โ 90% |
| LambdaLinear10PercentEvery1Minute | 10% โ 20% โ ... โ 100% (every 1 min) |
| LambdaLinear10PercentEvery2Minutes | 10% โ 20% โ ... โ 100% (every 2 min) |
| LambdaLinear10PercentEvery3Minutes | 10% โ 20% โ ... โ 100% (every 3 min) |
| LambdaLinear10PercentEvery10Minutes | 10% โ 20% โ ... โ 100% (every 10 min) |
- Canary = shift small %, wait, then shift ALL remaining
- Linear = shift same % at regular intervals until 100%
ECS Deployment Configurationsโ
| Configuration | Behavior |
|---|---|
| ECSAllAtOnce | Shift 100% immediately |
| ECSCanary10Percent5Minutes | Same as Lambda canary |
| ECSLinear10PercentEvery1Minute | Same as Lambda linear |
Lifecycle Hooksโ
EC2/On-Premises Hook Orderโ
ApplicationStop โ Stop current app
โ
DownloadBundle โ Download new revision from S3/GitHub
โ
BeforeInstall โ Pre-install tasks (backup, decrypt)
โ
Install โ Copy files to destination
โ
AfterInstall โ Post-install (set permissions, config)
โ
ApplicationStart โ Start the application
โ
ValidateService โ Run health checks โ MOST IMPORTANT
Lambda Hook Orderโ
BeforeAllowTraffic โ Run pre-traffic validation Lambda
โ
AllowTraffic โ Traffic shifted to new version
โ
AfterAllowTraffic โ Run post-traffic validation Lambda
Pre-Traffic Hook Example (Lambda)โ
public class PreTrafficHook implements RequestHandler<Map<String, Object>, Void> {
private final CodeDeployClient codeDeploy = CodeDeployClient.create();
public Void handleRequest(Map<String, Object> event, Context context) {
String deploymentId = (String) event.get("DeploymentId");
String lifecycleEventHookExecutionId = (String) event.get("LifecycleEventHookExecutionId");
String status = "Succeeded";
try {
// Test the new Lambda version
invokeNewVersion();
validateResponse();
} catch (Exception e) {
status = "Failed"; // This triggers automatic rollback
}
codeDeploy.putLifecycleEventHookExecutionStatus(
PutLifecycleEventHookExecutionStatusRequest.builder()
.deploymentId(deploymentId)
.lifecycleEventHookExecutionId(lifecycleEventHookExecutionId)
.status(status)
.build());
return null;
}
}
appspec.ymlโ
Lambdaโ
version: 0.0
Resources:
- MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Name: "OrderProcessor"
Alias: "live"
CurrentVersion: "1"
TargetVersion: "2"
Hooks:
- BeforeAllowTraffic: "arn:aws:lambda:us-east-1:123:function:PreTrafficHook"
- AfterAllowTraffic: "arn:aws:lambda:us-east-1:123:function:PostTrafficHook"
EC2โ
version: 0.0
os: linux
files:
- source: /
destination: /var/www/html
permissions:
- object: /var/www/html
owner: apache
group: apache
mode: "755"
hooks:
ApplicationStop:
- location: scripts/stop-server.sh
timeout: 120
BeforeInstall:
- location: scripts/install-deps.sh
timeout: 300
AfterInstall:
- location: scripts/set-permissions.sh
ApplicationStart:
- location: scripts/start-server.sh
timeout: 120
ValidateService:
- location: scripts/health-check.sh
timeout: 60
ECS Blue/Greenโ
version: 0.0
Resources:
- TargetService:
Type: AWS::ECS::Service
Properties:
TaskDefinition: "arn:aws:ecs:us-east-1:123:task-definition/my-task:2"
LoadBalancerInfo:
ContainerName: "api-container"
ContainerPort: 8080
Hooks:
- BeforeInstall: "LambdaValidateDatabases"
- AfterInstall: "LambdaRunIntegrationTests"
- AfterAllowTestTraffic: "LambdaVerifyGreenTargetGroup"
- BeforeAllowTraffic: "LambdaCheckHealth"
- AfterAllowTraffic: "LambdaVerifyProductionShifting"
Rollback Behaviorโ
| Trigger | Rollback |
|---|---|
| Any lifecycle hook fails | โ Automatic |
| CloudWatch alarm breached | โ Automatic (if configured) |
| Manual trigger | โ Via console/CLI |
CodeDeploy "rollback" = redeploy the previous revision. It doesn't reverse changes โ it deploys the old version as a new deployment.
Deployment Groupsโ
| Config | Description |
|---|---|
| Deployment group | Target instances (EC2 tags, ASG, ECS service) |
| Deployment config | Traffic shifting strategy |
| Service role | IAM role for CodeDeploy |
| Alarms | CloudWatch alarms that trigger rollback |
| Triggers | SNS notifications on deployment events |
| Auto-rollback | Enable/disable on failure or alarm |
๐ฏ DVA-C02 Exam Tipsโ
- Canary = shift small %, wait, shift rest. Linear = gradual increment
- Hook failure = automatic rollback
- Rollback = redeploy previous version (new deployment)
- EC2 supports in-place AND blue/green. ECS = blue/green only
- Lambda uses aliases for traffic shifting
- BeforeAllowTraffic = pre-traffic validation (Lambda platform)
- ValidateService = health check (EC2 platform)
- appspec.yml = mandatory deployment specification file
- CodeDeploy Agent needed on EC2, NOT needed for Lambda/ECS
- ECS blue/green requires ALB with two target groups
๐งช Practice Questionsโ
Q1. ValidateService hook fails. What happens?
A) Deployment marked failed, no rollback
B) Automatic rollback to previous version
C) Hook retries 3 times
D) Deployment continues with warning
โ Answer & Explanation
B โ Any hook failure triggers automatic rollback by redeploying the last successful version.
Q2. 10% traffic to new Lambda, wait 5 min, then 100%. Which config?
A) LambdaLinear10PercentEvery1Minute
B) LambdaAllAtOnce
C) LambdaCanary10Percent5Minutes
D) LambdaBlueGreen
โ Answer & Explanation
C โ Canary10Percent5Minutes: 10% immediate โ monitor 5 min โ shift remaining 90%.
Q3. ECS Fargate needs zero-downtime deployment. Which strategy?
A) In-place
B) Rolling update
C) Blue/Green with ALB target group swap
D) AllAtOnce
โ Answer & Explanation
C โ ECS Fargate with CodeDeploy supports only Blue/Green via ALB target group swapping.