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โ€‹