Skip to main content

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

PlatformDeployment TypeAgentTraffic Control
EC2/On-PremisesIn-place or Blue/Greenβœ… CodeDeploy AgentASG, tags
LambdaTraffic shifting (aliases)❌ Not neededAlias routing
ECSBlue/Green (ALB)❌ Not neededTarget group swap

Deployment Strategies

EC2 Deployment Strategies

StrategyDescriptionDowntime
AllAtOnceDeploy to all instances simultaneously⚠️ Brief
HalfAtATimeDeploy to 50% of instances, then remainingMinimal
OneAtATimeDeploy to one instance at a timeNone
Blue/GreenCreate new ASG, shift ALB trafficNone

Lambda Deployment Configurations

ConfigurationBehavior
LambdaAllAtOnceShift 100% traffic immediately
LambdaCanary10Percent5Minutes10% β†’ wait 5 min β†’ 90%
LambdaCanary10Percent10Minutes10% β†’ wait 10 min β†’ 90%
LambdaCanary10Percent15Minutes10% β†’ wait 15 min β†’ 90%
LambdaCanary10Percent30Minutes10% β†’ wait 30 min β†’ 90%
LambdaLinear10PercentEvery1Minute10% β†’ 20% β†’ ... β†’ 100% (every 1 min)
LambdaLinear10PercentEvery2Minutes10% β†’ 20% β†’ ... β†’ 100% (every 2 min)
LambdaLinear10PercentEvery3Minutes10% β†’ 20% β†’ ... β†’ 100% (every 3 min)
LambdaLinear10PercentEvery10Minutes10% β†’ 20% β†’ ... β†’ 100% (every 10 min)
Canary vs Linear
  • Canary = shift small %, wait, then shift ALL remaining
  • Linear = shift same % at regular intervals until 100%

ECS Deployment Configurations

ConfigurationBehavior
ECSAllAtOnceShift 100% immediately
ECSCanary10Percent5MinutesSame as Lambda canary
ECSLinear10PercentEvery1MinuteSame 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

TriggerRollback
Any lifecycle hook failsβœ… Automatic
CloudWatch alarm breachedβœ… Automatic (if configured)
Manual triggerβœ… Via console/CLI
Important

CodeDeploy "rollback" = redeploy the previous revision. It doesn't reverse changes β€” it deploys the old version as a new deployment.


Deployment Groups

ConfigDescription
Deployment groupTarget instances (EC2 tags, ASG, ECS service)
Deployment configTraffic shifting strategy
Service roleIAM role for CodeDeploy
AlarmsCloudWatch alarms that trigger rollback
TriggersSNS notifications on deployment events
Auto-rollbackEnable/disable on failure or alarm

DVA-C02 Exam Tips

CodeDeploy Exam Cheat Sheet
  1. Canary = shift small %, wait, shift rest. Linear = gradual increment
  2. Hook failure = automatic rollback
  3. Rollback = redeploy previous version (new deployment)
  4. EC2 supports in-place AND blue/green. ECS = blue/green only
  5. Lambda uses aliases for traffic shifting
  6. BeforeAllowTraffic = pre-traffic validation (Lambda platform)
  7. ValidateService = health check (EC2 platform)
  8. appspec.yml = mandatory deployment specification file
  9. CodeDeploy Agent needed on EC2, NOT needed for Lambda/ECS
  10. 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.


Resources

πŸ“–
Track Page Progress0 / 635 Read
Knowledge Base Completion0%