Ace Cloud Interviews
Home/AWS Tutorial/CodeDeploy
🛠️

AWS Developer Tools & CI/CD

CodeDeploy

Automate application deployments to EC2, Lambda, ECS, and on-premises servers

AWS CodeDeploy automates application deployments to EC2 instances, Lambda functions, ECS services, and on-premises servers, enabling consistent and repeatable releases without manual SSH steps. It supports rolling, blue/green, and canary deployment strategies with automatic rollback on failure, making it a critical service for zero-downtime deployments.

Deployment Targets: EC2, Lambda, ECS, On-Premises

CodeDeploy uses the concept of a "compute platform" which determines how deployments work fundamentally:

PlatformWhat DeploysAgent RequiredKey Use Case
EC2/On-PremisesRevision (zip/tar from S3 or GitHub)Yes - CodeDeploy agent on instanceTraditional app deployments to servers
LambdaLambda function version shiftNo - API-drivenCanary/linear traffic shifting for functions
ECSECS task definition revisionNo - API-drivenBlue/green container deployments

For EC2 deployments, the CodeDeploy agent must be installed on every instance. It polls CodeDeploy for pending deployments and executes the appspec.yml lifecycle hooks.

bash
# Install CodeDeploy agent on Amazon Linux 2
yum install -y ruby wget
cd /home/ec2-user
wget https://bucket-name.s3.region.amazonaws.com/latest/install
chmod +x ./install
./install auto
systemctl enable codedeploy-agent
systemctl start codedeploy-agent

AppSpec File and Lifecycle Event Hooks

The appspec.yml file defines how CodeDeploy deploys your application. Its structure differs between EC2/On-Premises and Lambda/ECS.

EC2/On-Premises appspec.yml:

bash
version: 0.0
os: linux
files:
  - source: /
    destination: /var/www/myapp
permissions:
  - object: /var/www/myapp
    owner: www-data
    group: www-data
    mode: "755"
hooks:
  BeforeInstall:
    - location: scripts/stop_server.sh
      timeout: 60
      runas: root
  AfterInstall:
    - location: scripts/install_dependencies.sh
      timeout: 120
  ApplicationStart:
    - location: scripts/start_server.sh
      timeout: 60
  ValidateService:
    - location: scripts/validate.sh
      timeout: 60

EC2 lifecycle event order for a standard (in-place) deployment:

HookWhen It RunsTypical Action
ApplicationStopBefore new revision is downloadedGracefully stop old app
DownloadBundleCodeDeploy downloads revisionAutomatic - no hook
BeforeInstallBefore files are copiedPre-install setup, backup
InstallFiles are copied to destinationAutomatic - no hook
AfterInstallAfter files are copiedSet permissions, config files
ApplicationStartStart the applicationStart service/process
ValidateServiceVerify app is running correctlyHealth check, smoke test
⚠️

If ApplicationStop fails on the FIRST deployment to a new instance (because there is no running app to stop), CodeDeploy will mark the deployment as failed. Use "exit 0" defensively in ApplicationStop scripts when the application may not be running.

Deployment Strategies: In-Place, Rolling, Blue/Green, Canary

CodeDeploy supports multiple deployment strategies. The right choice depends on your downtime tolerance, rollback requirements, and infrastructure cost constraints.

StrategyPlatformHow It WorksRollback SpeedCost
All-at-once (in-place)EC2Deploy to all instances simultaneouslyRedeploy (slow)No extra cost
RollingEC2Deploy to one batch at a time, rest stay liveRedeployNo extra cost
Rolling with additional batchEC2Spin up extra instances, deploy, remove oldRedeployBrief extra instance cost
Blue/Green (EC2)EC2New ASG created, traffic shifted at ALBRe-route to blue (fast)Double capacity briefly
Blue/Green (ECS)ECSNew task set created, traffic shifted at ALBRe-route to blue (instant)Double task capacity briefly
Canary (Lambda)LambdaX% to new version, 100% after intervalRollback alias (instant)No extra cost
Linear (Lambda)LambdaIncrement % each interval until 100%Rollback alias (instant)No extra cost
💡

For ECS Blue/Green deployments, CodeDeploy integrates with an Application Load Balancer. It creates a new task set (green), routes test traffic to a test listener, then shifts production traffic. The original task set (blue) stays live for the configured termination time, enabling instant rollback.

Automatic Rollback and CloudWatch Alarm Integration

CodeDeploy can automatically roll back when a deployment fails or when a CloudWatch alarm fires. This is a key resilience feature for production deployments.

Rollback TriggerHow to ConfigureBehavior
Deployment failureEnable automatic rollback on failure in deployment groupRe-deploys last successful revision
CloudWatch alarmAssociate alarms with deployment groupStops in-progress deploy, re-deploys last good revision
Manual rollbackRedeploy a previous revision via console or CLIExplicit operator action
bash
# Trigger a manual rollback by redeploying the last successful revision
aws deploy create-deployment \
  --application-name my-app \
  --deployment-group-name my-dg \
  --deployment-config-name CodeDeployDefault.OneAtATime \
  --auto-rollback-configuration enabled=true,events=DEPLOYMENT_FAILURE \
  --description "Rollback to previous version"

# Check deployment status
aws deploy get-deployment --deployment-id d-XXXXXXXXX
⚠️

Automatic rollback re-runs the appspec.yml lifecycle hooks in reverse order. If your ApplicationStop script is not idempotent, a rollback can fail. Always write deployment scripts defensively to handle being run multiple times.

IAM Roles: Service Role vs Instance Profile

CodeDeploy requires two distinct IAM entities that are commonly confused:

IAM EntityAttached ToPurposeKey Permissions
CodeDeploy service roleDeployment groupAllows CodeDeploy to call EC2, ELB, ASG, ECS APIsAWSCodeDeployRole managed policy
EC2 instance profileEC2 instances in deployment groupAllows agent on instance to download revision from S3s3:GetObject on the artifact bucket
💡

A common setup mistake is attaching the wrong role type. The CodeDeploy service role goes on the deployment group configuration - not on the EC2 instance. The instance profile goes on the EC2 instance. Getting this backwards causes either permission errors or deployment failures.

🎯

Interview Focus Points

  • 1What is the difference between in-place and blue/green deployment in CodeDeploy?
  • 2Walk me through the lifecycle event hooks for an EC2 deployment in order.
  • 3How does CodeDeploy integrate with an Application Load Balancer for blue/green deployments?
  • 4How does CodeDeploy handle rollbacks - what triggers them and what happens?
  • 5What two IAM roles are required for a CodeDeploy EC2 deployment and why?
  • 6How does the CodeDeploy agent work and where does it need to be installed?
  • 7What are the different deployment strategies for Lambda functions in CodeDeploy?
  • 8What happens if ApplicationStop fails on the first deployment to a new instance?
  • 9How do you integrate CloudWatch alarms with a CodeDeploy deployment group?