Prev Next

Cloud / AWS CodeDeploy Interview questions

Last updated

1. What is AWS CodeDeploy? 2. What are the compute platforms supported by AWS CodeDeploy? 3. What are the main components of AWS CodeDeploy? 4. What is a deployment group in CodeDeploy? 5. What is a revision in AWS CodeDeploy? 6. What is the CodeDeploy agent? 7. What is an AppSpec file? 8. What are the types of deployments in AWS CodeDeploy? 9. What are lifecycle event hooks in CodeDeploy? 10. What is a deployment configuration in CodeDeploy? 11. What are the predefined deployment configurations for EC2/on-premises? 12. What are the revision sources supported by CodeDeploy? 13. What is the purpose of the CodeDeploy service role? 14. What is the purpose of the EC2 instance profile in CodeDeploy? 15. How do you create a deployment using the AWS CLI? 16. What are the sections of an EC2 AppSpec file? 17. How do you deploy to on-premises servers using CodeDeploy? 18. How do you install the CodeDeploy agent? 19. Where are CodeDeploy agent and deployment logs stored? 20. How much does AWS CodeDeploy cost? 21. What is the difference between in-place and blue/green deployments? 22. Explain the lifecycle event order of an in-place deployment? 23. Explain the execution flow of a blue/green deployment on EC2? 24. Which environment variables are available to CodeDeploy hook scripts? 25. How does CodeDeploy use minimum healthy hosts? 26. How does CodeDeploy integrate with Elastic Load Balancing? 27. How does CodeDeploy work with Auto Scaling groups? 28. How does automatic rollback work in CodeDeploy? 29. How do CloudWatch alarms stop a CodeDeploy deployment? 30. How do you send CodeDeploy deployment notifications? 31. What is the difference between CodeDeploy and Elastic Beanstalk? 32. What is the difference between CodeDeploy and CodePipeline? 33. How does CodeDeploy deploy AWS Lambda functions? 34. What is the difference between canary and linear deployments? 35. How does CodeDeploy deploy to Amazon ECS? 36. What are the AppSpec hooks for Lambda and ECS deployments? 37. How do you write a Lambda validation hook for CodeDeploy? 38. How do you use CodeDeploy with AWS SAM? 39. How does file_exists_behavior work in CodeDeploy? 40. How do tag groups select instances in a deployment group? 41. What happens when the ApplicationStop script fails in CodeDeploy? 42. What happens when a deployment fails on one instance? 43. How do you troubleshoot a failed CodeDeploy deployment? 44. How do you troubleshoot the HEALTH_CONSTRAINTS error in CodeDeploy? 45. How do you secure AWS CodeDeploy deployments? 46. How does the CodeDeploy agent communicate with the service? 47. How does CodeDeploy handle Auto Scaling scale-out during a deployment? 48. Explain the execution flow of a CodePipeline deployment to CodeDeploy? 49. How do you define CodeDeploy resources using CloudFormation? 50. How can you optimize CodeDeploy deployment time?

1. What is AWS CodeDeploy?

AWS CodeDeploy is a managed deployment service that automates releasing application code to Amazon EC2 instances, on-premises servers, AWS Lambda functions and Amazon ECS services. You hand it a packaged revision and a deployment plan, and it copies the files, runs your scripts, shifts traffic and rolls back when something goes wrong.

It replaces hand-run SSH sessions and one-off shell scripts in the release process. Because the revision can hold code, binaries, configuration or scripts, it is language-agnostic.

Core capabilities include in-place and blue/green deployments, canary and linear traffic shifting for Lambda and ECS, automatic rollback on failure or CloudWatch alarms, and integration with CodePipeline, Auto Scaling and Elastic Load Balancing.

Take quiz
Which task is AWS CodeDeploy designed for?
Compiling source code into build artifacts
Storing and scanning container images
Automating how a built revision is released to compute targets
Provisioning VPCs and subnets
Which set of targets can CodeDeploy deploy to?
Only EC2 instances
S3 buckets and CloudFront distributions
EKS clusters and Elastic Beanstalk environments
EC2 instances, on-premises servers, Lambda functions and ECS services

2. What are the compute platforms supported by AWS CodeDeploy?

CodeDeploy supports three compute platforms: EC2/On-Premises, AWS Lambda and Amazon ECS. The platform is picked when you create the application, and it decides which deployment types, AppSpec format and hooks apply.

Platform Deployment types AppSpec format Needs agent
EC2/On-Premises In-place, blue/green (EC2 only) YAML (appspec.yml) Yes
AWS Lambda Blue/green (traffic shifting) YAML or JSON No
Amazon ECS Blue/green (traffic shifting) YAML or JSON No

Amazon EKS is not a CodeDeploy compute platform, so Kubernetes rollouts use other tooling.

Take quiz
Which platform or platforms allow in-place deployments?
Lambda and ECS only
All three platforms
ECS and on-premises only
EC2/On-Premises only
Which AppSpec format is valid for an EC2/On-Premises deployment?
YAML, in a file named appspec.yml
JSON only
Either YAML or JSON
XML

3. What are the main components of AWS CodeDeploy?

CodeDeploy is built from a handful of objects that you configure once and reuse for every release.

  • Application - a named container that also fixes the compute platform.
  • Deployment group - the set of targets plus settings such as rollback, alarms and load balancer.
  • Deployment configuration - the pace rules, either minimum healthy hosts or a traffic-shifting schedule.
  • Revision - the versioned bundle you deploy, which contains the AppSpec file.
  • AppSpec file - the instructions for what to copy, which permissions to set and which hooks to run.
  • CodeDeploy agent - the process on EC2/on-premises servers that executes the instructions.
  • Service role and instance profile - the IAM identities used by the service and the agent.

A single deployment is the act of applying one revision to one deployment group using one configuration.

Take quiz
Where is the compute platform of a CodeDeploy setup chosen?
When you create the application
Inside the AppSpec hooks section
On the CodeDeploy agent configuration file
In the service role trust policy
Which component controls how fast a deployment proceeds and how many hosts must stay healthy?
Deployment group tags
Deployment configuration
Revision
Service role

4. What is a deployment group in CodeDeploy?

A deployment group defines where a revision is deployed and under which rules. For EC2/on-premises it identifies instances by tags, Auto Scaling groups or both. For Lambda it names the function, and for ECS it names the cluster and service.

It also carries the settings that do not belong inside a revision: the service role, deployment configuration, load balancer or target groups, triggers, CloudWatch alarms, rollback behavior and blue/green options.

One application usually has several deployment groups, such as dev, staging and prod. The same revision can be promoted through them while each group keeps its own safety settings.

Take quiz
How does one application typically support dev, staging and prod?
One AppSpec file per instance
One deployment group per environment
One service role per revision
One application must be created per instance
Which setting lives on the deployment group rather than in the revision?
The hooks section
The files section
Rollback and alarm configuration
The permissions section

5. What is a revision in AWS CodeDeploy?

A revision is the versioned unit that CodeDeploy ships. For EC2/on-premises it is an archive (zip, tar or tgz) holding your application files, scripts and an appspec.yml at the root of the bundle. For Lambda and ECS the revision is only an AppSpec file, stored in S3 or supplied inline.

EC2/on-premises revisions live in Amazon S3 or GitHub and are identified by the bucket, key and version or ETag, or by a commit ID. Turn on S3 versioning so a past revision can always be redeployed, since rollback depends on it.

aws deploy push \
  --application-name web-app \
  --s3-location s3://my-bucket/web-app-v12.zip \
  --source ./build

The push command zips the folder, uploads it and prints the matching create-deployment command.

Take quiz
Where must appspec.yml sit in an EC2/on-premises revision?
Inside a scripts folder
In the destination directory on the instance
At the root of the bundle
Next to the zip in the S3 bucket, outside the archive
What does a Lambda or ECS revision consist of?
A zip with application files and shell scripts
A Docker image tarball
A CloudFormation template
An AppSpec file only, in YAML or JSON

6. What is the CodeDeploy agent?

The CodeDeploy agent is a small service that runs on each EC2 or on-premises server. It polls CodeDeploy for work, downloads the revision, unpacks it and runs the lifecycle hooks from your AppSpec file. Lambda and ECS deployments do not use it.

It has to be installed and running before the first deployment, it needs outbound HTTPS to the CodeDeploy endpoints and to S3 or GitHub, and the instance needs credentials to read the revision. On Linux it runs as the codedeploy-agent service.

sudo service codedeploy-agent status
cat /etc/codedeploy-agent/conf/codedeployagent.yml

Unpacked bundles are cached under /opt/codedeploy-agent/deployment-root.

Take quiz
Which deployments require the CodeDeploy agent?
Lambda deployments
ECS deployments
Only blue/green deployments
EC2/On-Premises deployments
What does the agent do with a downloaded revision?
Unpacks it and runs the hooks defined in appspec.yml in order
Uploads it back to S3 for auditing
Converts it into an AMI
Forwards it to CloudFormation

7. What is an AppSpec file?

The AppSpec file tells CodeDeploy what to do during a deployment. Its structure depends on the compute platform, but it always starts with version: 0.0, which is the only value currently accepted.

Platform File name Main sections
EC2/On-Premises appspec.yml at bundle root os, files, permissions, hooks
AWS Lambda YAML or JSON Resources (function name, alias, current and target version), Hooks
Amazon ECS YAML or JSON Resources (task definition, container name and port), Hooks

Indentation mistakes are a common cause of failures, so validate the YAML before packaging.

Take quiz
What does the Lambda AppSpec Resources block describe?
Function name, alias, current version and target version
Instance tags and IAM roles
Source and destination file paths
Load balancer listener ARNs
Which value is used for the version field in an AppSpec file?
1.0
0.0
2.0
latest

8. What are the types of deployments in AWS CodeDeploy?

CodeDeploy offers two deployment types: in-place and blue/green.

In an in-place deployment the application on the existing instances is stopped, the new revision is installed and the application is started again, usually in batches so the fleet keeps serving traffic. It is available only for EC2/on-premises.

In a blue/green deployment the new version runs in a separate environment and traffic is moved over once it is ready. For EC2 this means replacement instances behind a load balancer. For Lambda and ECS, blue/green is the only option and works by shifting traffic between versions or task sets.

Take quiz
Which deployment type is the only one available for Lambda?
In-place
Blue/green through traffic shifting
Rolling in-place
Either one, chosen per function
What does an EC2 blue/green deployment require?
An on-premises server
A second AWS account
A load balancer that can shift traffic to replacement instances
A Lambda alias

9. What are lifecycle event hooks in CodeDeploy?

Lifecycle event hooks are the points in a deployment where your own logic runs. On EC2/on-premises a hook points to a script. On Lambda and ECS a hook names a Lambda function that validates the release.

A script hook can set location, timeout (default 3600 seconds) and runas. A non-zero exit code or a timeout fails the event.

hooks:
  BeforeInstall:
    - location: scripts/stop_app.sh
      timeout: 300
      runas: root
  ValidateService:
    - location: scripts/health_check.sh
      timeout: 120

Platform Hooks you can use
EC2/On-Premises ApplicationStop, BeforeInstall, AfterInstall, ApplicationStart, ValidateService, plus load balancer hooks
AWS Lambda BeforeAllowTraffic, AfterAllowTraffic
Amazon ECS BeforeInstall, AfterInstall, AfterAllowTestTraffic, BeforeAllowTraffic, AfterAllowTraffic

Take quiz
What makes a hook script fail its lifecycle event?
Writing text to stdout
Running longer than 10 seconds
A non-zero exit code or a timeout
Having a .sh file extension
Which ECS hook runs after test traffic has been routed to the replacement task set?
BeforeInstall
AfterAllowTraffic
ValidateService
AfterAllowTestTraffic

10. What is a deployment configuration in CodeDeploy?

A deployment configuration sets the pace and the success rules of a deployment. For EC2/on-premises it defines the minimum healthy hosts, as a number or a percentage. For Lambda and ECS it defines the traffic-shifting schedule: all at once, canary or linear.

AWS ships predefined configurations, and you can create custom ones. The deployment group holds a default, and you can override it when you start a deployment.

aws deploy create-deployment-config \
  --deployment-config-name Web75Percent \
  --minimum-healthy-hosts type=FLEET_PERCENT,value=75

With this setting at least 75 percent of the fleet must stay healthy, so a 12-instance fleet is updated at most three instances at a time.

Take quiz
For Lambda, what does a deployment configuration define?
Which instances carry a given tag
How many healthy hosts remain
The execution role of the function
How traffic shifts from the old version to the new one
What does --minimum-healthy-hosts type=FLEET_PERCENT,value=75 express?
At least 75 percent of the fleet must stay healthy during the deployment
Deploy to 75 percent of instances and then stop
Roll back after 75 seconds
Shift 75 percent of traffic immediately

11. What are the predefined deployment configurations for EC2/on-premises?

CodeDeploy provides three predefined configurations for EC2/on-premises deployments. They differ in how many instances are updated at the same time.

Configuration Behavior Trade-off
CodeDeployDefault.OneAtATime (default) Updates one instance at a time Safest, slowest
CodeDeployDefault.HalfAtATime Updates up to 50% of instances at once Balanced
CodeDeployDefault.AllAtOnce Updates as many instances as possible; succeeds if at least one succeeds Fastest, highest downtime risk

With OneAtATime, the deployment stops at the first failed instance, so a bad revision reaches only one host. If none fits, create a custom configuration with your own minimum healthy hosts value.

Take quiz
Which configuration is applied to EC2 deployments when you do not choose one?
CodeDeployDefault.OneAtATime
CodeDeployDefault.AllAtOnce
CodeDeployDefault.HalfAtATime
CodeDeployDefault.LambdaCanary10Percent5Minutes
Which predefined configuration carries the highest risk of full downtime?
CodeDeployDefault.OneAtATime
CodeDeployDefault.AllAtOnce
CodeDeployDefault.HalfAtATime

12. What are the revision sources supported by CodeDeploy?

For EC2/on-premises, CodeDeploy can pull a revision directly from Amazon S3 or GitHub. S3 revisions must be a zip, tar or tgz archive, and you should reference a specific object version. GitHub revisions are identified by repository and commit ID, and CodeDeploy needs an authorized GitHub connection.

For Lambda and ECS the AppSpec file can come from S3 or be pasted inline when you create the deployment.

Other repositories such as AWS CodeCommit or Bitbucket are not direct sources. The usual pattern is to let CodePipeline or a CI job package the code into a zip in S3, then deploy that archive.

Take quiz
Which repository can CodeDeploy pull a revision from directly?
AWS CodeCommit
GitHub
Bitbucket
Docker Hub
Which archive formats can an S3 revision use?
rar and 7z
jar and war only
zip, tar or tgz
An unpacked folder

13. What is the purpose of the CodeDeploy service role?

The service role is the IAM role CodeDeploy assumes to act on your behalf. It lets the service read instance tags, describe Auto Scaling groups, register and deregister instances with load balancers, read CloudWatch alarms and publish to SNS. It is attached to the deployment group.

Its trust policy must allow the CodeDeploy service principal:

{
  "Effect": "Allow",
  "Principal": { "Service": "codedeploy.amazonaws.com" },
  "Action": "sts:AssumeRole"
}

AWS provides managed policies per platform: AWSCodeDeployRole for EC2/on-premises, AWSCodeDeployRoleForLambda and AWSCodeDeployRoleForECS.

Start from the managed policy and add only what your setup needs. For example, blue/green copies of Auto Scaling groups that use encrypted EBS volumes require extra KMS permissions on the role.

Take quiz
Which principal must the CodeDeploy service role trust?
ec2.amazonaws.com
lambda.amazonaws.com
codedeploy.amazonaws.com
codebuild.amazonaws.com
What is the service role attached to?
The EC2 instance
The S3 revision bucket
The AppSpec file
The deployment group

14. What is the purpose of the EC2 instance profile in CodeDeploy?

The instance profile gives the CodeDeploy agent on an EC2 instance the permissions it needs, mainly to download the revision from S3 (such as s3:Get* and s3:List* on the revision bucket). Without it deployments fail with credential errors before any hook runs.

It is different from the service role, which belongs to the CodeDeploy service itself.

Service role Instance profile
Used by CodeDeploy service CodeDeploy agent on the instance
Attached to Deployment group EC2 instance or launch template
Typical permissions Describe instances, ASGs, ELB, alarms Read revision from S3

On-premises servers cannot use an instance profile, so they authenticate with an IAM user or an IAM role session instead.

Take quiz
Who uses the instance profile credentials during a deployment?
The CodeDeploy service
The load balancer
The CloudFormation stack
The CodeDeploy agent on the instance
What is the minimum S3 access an instance needs for S3-based revisions?
Read access to the bucket holding the revisions
Write access to every bucket in the account
ec2:TerminateInstances
iam:PassRole on the service role

15. How do you create a deployment using the AWS CLI?

You package and upload a revision, start the deployment, then watch its status.

  1. Push the bundle to S3 with aws deploy push.
  2. Start the deployment with aws deploy create-deployment.
  3. Track it with aws deploy get-deployment, or block until it finishes with aws deploy wait.
aws deploy push --application-name web-app \
  --s3-location s3://my-bucket/web-app-v12.zip --source ./build

aws deploy create-deployment \
  --application-name web-app \
  --deployment-group-name prod \
  --s3-location bucket=my-bucket,key=web-app-v12.zip,bundleType=zip \
  --description "release 12"

aws deploy wait deployment-successful --deployment-id d-ABCDE1234

Use list-deployment-instances to see which individual instances failed.

Take quiz
Which command packages local files and uploads them as a revision to S3?
aws deploy push
aws deploy register
aws deploy create-application
aws s3 deploy
Which command reports the status of a specific deployment?
aws deploy list-applications
aws deploy get-deployment
aws deploy push
aws deploy register-on-premises-instance

16. What are the sections of an EC2 AppSpec file?

An EC2/on-premises appspec.yml has five top-level parts: version, os, files, permissions and hooks.

version: 0.0
os: linux
files:
  - source: /app
    destination: /var/www/app
permissions:
  - object: /var/www/app
    pattern: "**"
    owner: webapp
    mode: 755
hooks:
  ApplicationStop:
    - location: scripts/stop.sh
  AfterInstall:
    - location: scripts/configure.sh
  ApplicationStart:
    - location: scripts/start.sh
  ValidateService:
    - location: scripts/check.sh
      timeout: 60

  • os - linux or windows.
  • files - which files from the bundle are copied where.
  • permissions - owner, group, mode and ACLs applied to the copied files.
  • hooks - scripts to run at each lifecycle event.
Take quiz
Which AppSpec section copies revision files onto the instance?
permissions
files
hooks
os
What does the permissions section control?
IAM permissions of the agent
Which users may start a deployment
Owner, group and mode of the copied files
S3 bucket policies

17. How do you deploy to on-premises servers using CodeDeploy?

On-premises servers are registered, tagged and then targeted like EC2 instances. Only in-place deployments are supported for them.

  1. Create an IAM identity for the server. An IAM role session with temporary credentials is preferred over a long-lived IAM user.
  2. Register the server with aws deploy register-on-premises-instance.
  3. Tag it with aws deploy add-tags-to-on-premises-instances.
  4. Install the agent and place the on-premises configuration file with the credentials and region.
  5. Point a deployment group at the tag and run a deployment.

The server needs outbound HTTPS to the CodeDeploy and S3 endpoints. Each instance update is billed at a small per-update rate.

Take quiz
Which deployment type is available for on-premises instances?
Blue/green
Canary
In-place
Linear
How are registered on-premises instances selected by a deployment group?
By Auto Scaling group name
By VPC ID
By Lambda alias
By tags

18. How do you install the CodeDeploy agent?

On Linux you download the installer from the regional CodeDeploy S3 bucket and run it, or let Systems Manager do it. The console can create an AWS Systems Manager association that installs the agent and keeps it updated.

sudo yum update -y
sudo yum install -y ruby wget
cd /home/ec2-user
wget https://aws-codedeploy-us-east-1.s3.us-east-1.amazonaws.com/latest/install
chmod +x ./install
sudo ./install auto
sudo service codedeploy-agent status

Replace the region in the URL with your own. For Auto Scaling groups, bake the agent into the AMI or install it from user data in the launch template, otherwise new instances cannot receive deployments.

Take quiz
Which command checks the agent on Amazon Linux?
aws deploy agent-status
systemctl status aws-deploy
codedeploy --health
sudo service codedeploy-agent status
What is the most reliable way to make sure new Auto Scaling instances have the agent?
Bake it into the AMI or install it from launch template user data
SSH to each new instance and install it
Declare it in the AppSpec os section
Attach the service role to the launch template

19. Where are CodeDeploy agent and deployment logs stored?

On Linux instances the agent writes three main logs:

Log Path
Agent log /var/log/aws/codedeploy-agent/codedeploy-agent.log
Deployment log /opt/codedeploy-agent/deployment-root/deployment-logs/codedeploy-agent-deployments.log
Hook script output /opt/codedeploy-agent/deployment-root/<group-id>/<deployment-id>/logs/scripts.log

On Windows the logs are under C:\ProgramData\Amazon\CodeDeploy\log. Start with scripts.log when a hook fails, since it contains the stdout and stderr of your scripts. To avoid logging in to servers, ship these files to CloudWatch Logs with the CloudWatch agent.

The console also lists every lifecycle event with its status and error message, and aws deploy get-deployment-instance returns the same per-event detail from the CLI. If the logs are too quiet, enable the :verbose: setting in codedeployagent.yml and restart the agent.

Take quiz
Where is the output of hook scripts recorded for a given deployment?
scripts.log in the deployment's logs folder
CloudTrail event history
The S3 revision bucket
The load balancer access log
What is the practical way to centralize instance-level deployment logs?
Enable S3 versioning on the revision bucket
Ship them to CloudWatch Logs with the CloudWatch agent
Add a ValidateService hook
Turn on the AppSpec debug flag

20. How much does AWS CodeDeploy cost?

There is no additional charge for deployments to EC2, Lambda and ECS. You only pay for the underlying resources, such as the instances and the S3 storage for revisions.

For on-premises servers, CodeDeploy charges $0.02 per on-premises instance update. A deployment to three instances is three updates, and instances that are skipped are not charged. Check the AWS pricing page for current rates, since prices can change by Region.

The real cost driver is usually what surrounds CodeDeploy. A blue/green EC2 deployment runs two fleets at once, so shortening the wait before original instances are terminated saves money. CloudWatch alarms, Lambda hook invocations and S3 requests are billed by their own services.

Take quiz
How does CodeDeploy bill on-premises deployments?
A flat monthly fee per application
$0.02 per on-premises instance update
Per GB of revision stored
It is always free
A deployment targets 3 on-premises instances and 1 is skipped. How many billable updates result?
3
1
2
0

21. What is the difference between in-place and blue/green deployments?

An in-place deployment updates the application on the instances that are already running. A blue/green deployment builds a replacement environment, moves traffic to it and then retires the original.

Aspect In-place Blue/green
Targets Existing instances New replacement instances (EC2) or new version/task set (Lambda, ECS)
Platforms EC2/On-Premises EC2, Lambda, ECS
Capacity during release Reduced while instances update Full capacity kept, extra capacity temporarily added
Rollback Redeploy previous revision Reroute traffic back to the original
Load balancer Optional Required for EC2
Cost Lowest Higher while both environments exist

Choose in-place for on-premises servers, stateful hosts or tight budgets. Choose blue/green for customer-facing production where fast rollback and untouched capacity matter more than temporary extra cost.

Take quiz
Which approach gives the fastest rollback?
In-place, by reinstalling the old version on every host
Both take exactly the same time
Blue/green, by rerouting traffic back to the original environment
Neither supports rollback
Which statement about EC2 blue/green deployments is true?
They only work on on-premises servers
They reuse the same instances as the old version
They do not need a load balancer
They need a load balancer and temporarily run extra instances

22. Explain the lifecycle event order of an in-place deployment?

In an in-place deployment the agent walks through a fixed sequence of events on every instance. Your scripts hang off the events in the middle.

flowchart LR
  A[ApplicationStop] --> B[DownloadBundle]
  B --> C[BeforeInstall]
  C --> D[Install]
  D --> E[AfterInstall]
  E --> F[ApplicationStart]
  F --> G[ValidateService]
  1. ApplicationStop - stops the running app, using the script from the previous revision.
  2. DownloadBundle - the agent fetches the revision.
  3. BeforeInstall - backups, cleanup, dependency prep.
  4. Install - the agent copies files to their destinations.
  5. AfterInstall - configuration, file permissions, migrations.
  6. ApplicationStart - starts the new version.
  7. ValidateService - health or smoke checks.

When a load balancer is attached, BeforeBlockTraffic, BlockTraffic and AfterBlockTraffic run first, and BeforeAllowTraffic, AllowTraffic and AfterAllowTraffic run last. DownloadBundle, Install, BlockTraffic and AllowTraffic are handled by the agent and cannot run your scripts.

Take quiz
Which hook is the natural place to set configuration after the files have been copied?
BeforeInstall
ApplicationStop
ValidateService
AfterInstall
Which pair of events cannot run custom scripts?
DownloadBundle and Install
BeforeInstall and AfterInstall
ApplicationStart and ValidateService
ApplicationStop and ValidateService

23. Explain the execution flow of a blue/green deployment on EC2?

A blue/green deployment on EC2 creates the new ("green") instances, installs the revision on them, and only then moves load balancer traffic away from the old ("blue") instances.

flowchart TD
  A["Provision replacement instances"] --> B["Install revision and run hooks"]
  B --> C{Wait for approval?}
  C -- Yes --> D["Manual reroute approval"]
  C -- No --> E["Register replacement instances with load balancer"]
  D --> E
  E --> F["Deregister original instances"]
  F --> G["Terminate or keep originals after wait time"]

Replacement instances are either created by copying the Auto Scaling group or chosen from tagged instances you launched yourself. The regular install events run on them, followed by BeforeAllowTraffic, AllowTraffic and AfterAllowTraffic.

The original instances run BeforeBlockTraffic, BlockTraffic and AfterBlockTraffic when they are taken out of rotation. They can be terminated after a configurable wait, or kept for debugging.

Take quiz
What happens to the original instances after traffic is rerouted?
They are deregistered, then terminated or kept according to the termination wait setting
They receive the new revision in place
They are always deleted immediately
They keep serving a small share of traffic permanently
On which instances do BeforeBlockTraffic and AfterBlockTraffic run?
The replacement instances
The original instances
The load balancer nodes
A Lambda function

24. Which environment variables are available to CodeDeploy hook scripts?

The agent exposes a few variables to every hook script on EC2/on-premises: APPLICATION_NAME, DEPLOYMENT_ID, DEPLOYMENT_GROUP_NAME, DEPLOYMENT_GROUP_ID and LIFECYCLE_EVENT.

The most useful one is DEPLOYMENT_GROUP_NAME, because it lets one revision behave differently in each environment without rebuilding it.

#!/bin/bash
set -e
case "$DEPLOYMENT_GROUP_NAME" in
  prod)    cp config/prod.env /var/www/app/.env ;;
  staging) cp config/staging.env /var/www/app/.env ;;
  *)       cp config/dev.env /var/www/app/.env ;;
esac
echo "$LIFECYCLE_EVENT finished for $DEPLOYMENT_ID" >> /var/log/app-deploy.log

This keeps the artifact identical across environments, which is what you want when promoting a tested build.

Take quiz
How can one hook script behave differently in staging and production?
Edit appspec.yml on each instance
Read DEPLOYMENT_GROUP_NAME and branch on it
Use a different AWS account for each script
Query the S3 bucket name
Which variable tells a script which lifecycle event is running?
DEPLOYMENT_STAGE
HOOK_NAME
LIFECYCLE_EVENT
AGENT_PHASE

25. How does CodeDeploy use minimum healthy hosts?

Minimum healthy hosts is the number or percentage of instances that must stay healthy during an EC2/on-premises deployment. CodeDeploy uses it to decide how many instances it can take offline at once, and whether the deployment as a whole succeeded.

An instance counts as healthy when its last deployment succeeded. An instance being updated is temporarily treated as unavailable, so the batch size is the fleet size minus the required healthy count. With 10 instances and a 70 percent minimum, at most three are updated at a time.

If too many instances fail, the deployment stops with a HEALTH_CONSTRAINTS error. If the requirement cannot be met at all, for example 100 percent healthy on an in-place deployment, the deployment fails before doing useful work.

Take quiz
A fleet has 10 instances and the minimum healthy hosts is 70 percent. What is the largest batch size?
7
1
3
5
What happens when the minimum healthy hosts requirement cannot be satisfied?
CodeDeploy silently switches to AllAtOnce
It pauses until an operator approves
It deploys only to healthy hosts and ignores the setting
The deployment fails with a health constraints error

26. How does CodeDeploy integrate with Elastic Load Balancing?

When a load balancer is attached to the deployment group, CodeDeploy takes each instance out of rotation before updating it and puts it back afterwards, so users do not hit a half-updated host.

  1. BlockTraffic deregisters the instance from the target group or Classic Load Balancer and waits for connection draining.
  2. The revision is installed and the application is restarted.
  3. AllowTraffic registers the instance again, and the load balancer health check decides whether it counts as healthy.

The catch is timing. The target group's deregistration delay (300 seconds by default) is applied to every instance, so a long delay multiplies across batches. Lower it if your requests are short. Application Load Balancers and Network Load Balancers use target groups, while Classic Load Balancers are attached by name.

Take quiz
What does the BlockTraffic event do?
Terminates the instance
Stops the application process
Closes SSH access
Deregisters the instance from the load balancer
Why can deployments behind an ALB feel slow?
The deregistration delay is applied to each instance as it is drained
The agent only polls once per hour
S3 downloads are capped at 1 MB/s
AppSpec files are parsed one line per minute

27. How does CodeDeploy work with Auto Scaling groups?

You can attach one or more Auto Scaling groups to a deployment group instead of, or alongside, tags. CodeDeploy then deploys to every instance in the group and keeps future instances in sync.

On attach, CodeDeploy adds a managed launch lifecycle hook to the Auto Scaling group. When the group scales out, the new instance is held in a pending state while CodeDeploy installs the last successful revision. Only after that does the instance go in service, so it never serves traffic without the application.

For blue/green deployments CodeDeploy copies the Auto Scaling group, deploys to the copy, reroutes traffic, and later deletes the original.

The AMI or launch template must already contain the CodeDeploy agent, and the service role needs Auto Scaling permissions.

Take quiz
What happens when an attached Auto Scaling group launches a new instance?
CodeDeploy installs the last successful revision through the launch lifecycle hook before the instance goes in service
The instance waits for the next manual deployment
The instance receives only the AppSpec file
CodeDeploy terminates it and launches another
Does a new Auto Scaling instance need the CodeDeploy agent already installed?
No, Auto Scaling installs it automatically
Yes, unless something installs it during launch
Only for Windows instances
Only for blue/green deployments

28. How does automatic rollback work in CodeDeploy?

You can enable automatic rollback on a deployment group for two triggers: a deployment failure and a CloudWatch alarm threshold being reached.

The mechanics depend on the platform:

  • EC2/on-premises in-place - CodeDeploy starts a new deployment of the last known good revision, with a new deployment ID. Files from the failed revision are removed.
  • EC2 blue/green - traffic is sent back to the original instances, if they have not been terminated.
  • Lambda and ECS - traffic is shifted back to the original version or task set.

Rollback needs something to roll back to. If there has never been a successful deployment, or the old revision was deleted from S3, the rollback itself fails. You can also stop a deployment manually and choose to roll back.

Take quiz
How does an automatic rollback of an in-place EC2 deployment work?
It restores an EBS snapshot of the instance
It redeploys the last known good revision as a new deployment
It reverts the AppSpec file through git
It terminates and relaunches each instance
When can a rollback not be performed?
When the deployment group uses tags
When SNS triggers are configured
When there is no previous successful revision available
When an Auto Scaling group is attached

29. How do CloudWatch alarms stop a CodeDeploy deployment?

You can attach up to 10 CloudWatch alarms to a deployment group. If any of them goes into the ALARM state while a deployment is running, CodeDeploy stops the deployment, and with automatic rollback enabled for alarms it then rolls back.

Pick alarms that measure user impact, such as 5xx count, p99 latency, or Lambda errors for the new version. Combined with a canary configuration, a small share of traffic exposes the problem before most users see it.

The service role needs permission to read alarm state. The option ignore poll alarm failure decides whether the deployment continues when CodeDeploy cannot retrieve an alarm's status, so set it deliberately.

Take quiz
Which alarm state makes CodeDeploy stop a deployment?
OK
INSUFFICIENT_DATA
ALARM
Any state change
Which pairing gives the earliest protection for a Lambda release?
AllAtOnce with no alarms
A linear configuration with alarms on unrelated metrics
An in-place configuration with alarms on S3 size
A canary configuration with an alarm on errors of the new version

30. How do you send CodeDeploy deployment notifications?

There are three common ways, and they can be combined.

  • Triggers on the deployment group publish deployment and instance events (start, success, failure, stop, rollback, ready) to an SNS topic. The topic policy must allow CodeDeploy to publish.
  • EventBridge rules match events such as CodeDeploy Deployment State-change Notification and route them to Lambda, SQS or Step Functions.
  • Notification rules in the Developer Tools console send selected events to SNS or to Slack and Microsoft Teams through AWS Chatbot.

Use EventBridge when you need to react to a deployment automatically, for example opening a ticket on failure. Use triggers or notification rules when people just need to be told.

Take quiz
Which mechanism lets you run automation when a deployment fails?
An AppSpec permissions entry
An S3 lifecycle rule
A deregistration delay
An EventBridge rule matching CodeDeploy state-change events
What must an SNS topic allow for CodeDeploy triggers to work?
Publishing from the CodeDeploy service
Subscriptions only from the service role
Access from the EC2 instance profile
Writes into the revision bucket

31. What is the difference between CodeDeploy and Elastic Beanstalk?

CodeDeploy only deploys code onto compute you already manage. Elastic Beanstalk is a platform service that provisions the environment (instances, load balancer, scaling) and deploys your application on it.

Aspect CodeDeploy Elastic Beanstalk
Scope Deployment automation only Infrastructure plus deployment
Targets EC2, on-premises, Lambda, ECS Beanstalk-managed environments
Control Custom hooks, AppSpec, traffic shifting Built-in deployment policies
Strategies In-place, blue/green, canary, linear All at once, rolling, immutable, traffic splitting
Best for Existing fleets and custom release flows Teams that want AWS to run the platform

Choose CodeDeploy when you already own the infrastructure or need on-premises and serverless targets. Choose Beanstalk when you want the platform handled for you.

Take quiz
Which service also provisions the instances and load balancer for your application?
Elastic Beanstalk
CodeDeploy
CodePipeline
AWS CodeBuild
Which service can deploy to on-premises servers?
Elastic Beanstalk
CodeDeploy
Amazon ECR
AWS Amplify

32. What is the difference between CodeDeploy and CodePipeline?

CodePipeline orchestrates the whole release workflow: source, build, test, approval and deploy stages. CodeDeploy does one job within that workflow, which is applying a revision to the target compute.

A typical flow is Source (repository), Build (CodeBuild creates the zip with appspec.yml), then a Deploy stage whose action calls CodeDeploy. The pipeline passes its output artifact to CodeDeploy as the revision.

They are independent. You can run CodeDeploy from the CLI or another CI system without CodePipeline, and CodePipeline can deploy using other providers such as CloudFormation or Elastic Beanstalk.

Take quiz
What is CodeDeploy's role inside a CodePipeline pipeline?
It builds the source code
It runs as the deploy action that applies the revision to the targets
It stores the pipeline artifacts
It triggers the pipeline on commits
Can CodeDeploy be used without CodePipeline?
No, it only starts from CodePipeline
Only for Lambda deployments
Yes, for example from the CLI or another CI tool
Only with a GitHub webhook

33. How does CodeDeploy deploy AWS Lambda functions?

CodeDeploy does not upload your function code. You publish a new function version first, and CodeDeploy then moves an alias from the current version to the target version by adjusting its weighted routing.

flowchart LR
  A["Publish new version"] --> B["BeforeAllowTraffic hook"]
  B --> C["Shift alias weight to new version"]
  C --> D["AfterAllowTraffic hook"]
  D --> E["Alias at 100 percent new version"]
  C -. alarm or hook failure .-> F["Shift back to old version"]
version: 0.0
Resources:
  - OrdersFunction:
      Type: AWS::Lambda::Function
      Properties:
        Name: "orders-api"
        Alias: "live"
        CurrentVersion: "6"
        TargetVersion: "7"
Hooks:
  - BeforeAllowTraffic: "PreTrafficCheck"
  - AfterAllowTraffic: "PostTrafficCheck" 

The deployment configuration decides whether the shift is canary, linear or all at once. Callers must invoke the alias, not a fixed version, or the shift has no effect.

Take quiz
What does CodeDeploy change to shift traffic between Lambda versions?
The function's IAM execution role
The function's memory setting
The weighted routing of a function alias
The API Gateway stage name
Why must clients invoke the alias rather than a specific version?
Versions cannot be invoked directly
Aliases are faster than versions
CodeDeploy only monitors aliases for cost
Traffic shifting works by changing where the alias points

34. What is the difference between canary and linear deployments?

Both shift traffic gradually on Lambda and ECS. Canary sends a small share first, waits, then moves the rest in one step. Linear moves traffic in equal increments at fixed intervals until it reaches 100 percent.

Type Pattern Predefined examples
Canary 10 percent, wait, then 100 percent CodeDeployDefault.LambdaCanary10Percent5Minutes, CodeDeployDefault.ECSCanary10Percent5Minutes
Linear 10 percent more every N minutes CodeDeployDefault.LambdaLinear10PercentEvery1Minute, CodeDeployDefault.ECSLinear10PercentEvery3Minutes
All at once 100 percent immediately CodeDeployDefault.LambdaAllAtOnce, CodeDeployDefault.ECSAllAtOnce

Canary suits a quick go/no-go decision from one small sample. Linear suits services where load-related problems appear gradually. Pair either with alarms so a bad release stops automatically.

Take quiz
What does CodeDeployDefault.LambdaCanary10Percent5Minutes do?
Adds 10 percent every 5 minutes
Deploys to 10 percent of instances only
Waits 10 minutes then rolls back
Sends 10 percent of traffic to the new version, waits 5 minutes, then sends the rest
How does a linear configuration move traffic?
In equal steps at fixed intervals until it reaches 100 percent
All at once after a manual approval
In one small batch and then everything
Only when CloudWatch alarms are disabled

35. How does CodeDeploy deploy to Amazon ECS?

ECS deployments are always blue/green. CodeDeploy creates a replacement task set running the new task definition, routes traffic to it in steps, then retires the original task set.

It requires an Application or Network Load Balancer with two target groups, a production listener and optionally a test listener, plus an ECS service that uses the CODE_DEPLOY deployment controller.

flowchart TD
  A["Create replacement task set"] --> B["Register with green target group"]
  B --> C["Route test traffic via test listener"]
  C --> D["AfterAllowTestTraffic hook"]
  D --> E["Shift production traffic per configuration"]
  E --> F["Terminate original task set after wait time"]
version: 0.0
Resources:
  - TargetService:
      Type: AWS::ECS::Service
      Properties:
        TaskDefinition: "arn:aws:ecs:us-east-1:111122223333:task-definition/web:7"
        LoadBalancerInfo:
          ContainerName: "web"
          ContainerPort: 8080
Hooks:
  - AfterAllowTestTraffic: "SmokeTestFunction" 

The test listener lets a Lambda hook exercise the new tasks before any real user traffic reaches them.

Take quiz
What does CodeDeploy create when deploying to ECS?
A replacement task set running the new task definition
A new ECS cluster
A new EC2 Auto Scaling group
A copy of the VPC
What load balancer setup does an ECS blue/green deployment need?
A single target group and no listeners
Two target groups and a production listener, with an optional test listener
One target group per task
A Classic Load Balancer with sticky sessions

36. What are the AppSpec hooks for Lambda and ECS deployments?

Lambda and ECS do not run shell scripts. Each hook in the AppSpec file names a Lambda function that CodeDeploy invokes, and the function reports success or failure back.

Platform Hook When it runs
Lambda BeforeAllowTraffic Before any traffic moves to the new version
Lambda AfterAllowTraffic After all traffic is on the new version
ECS BeforeInstall Before the replacement task set is created
ECS AfterInstall After the replacement task set is created
ECS AfterAllowTestTraffic After test traffic reaches the replacement task set
ECS BeforeAllowTraffic Before production traffic shifts
ECS AfterAllowTraffic After production traffic has shifted

A failed hook stops the deployment and triggers a rollback if it is enabled.

Take quiz
What does a hook entry in a Lambda or ECS AppSpec file reference?
A shell script path on the instance
The name of a Lambda function
An S3 object key
A CloudFormation output
Which Lambda hook runs before any production traffic reaches the new version?
AfterAllowTraffic
ValidateService
BeforeAllowTraffic
ApplicationStart

37. How do you write a Lambda validation hook for CodeDeploy?

A validation hook is a Lambda function that tests the new version, then calls PutLifecycleEventHookExecutionStatus with Succeeded or Failed. If it never reports, the deployment waits and eventually fails.

import boto3

codedeploy = boto3.client("codedeploy")
lam = boto3.client("lambda")

def handler(event, context):
    status = "Succeeded"
    try:
        resp = lam.invoke(FunctionName="orders-api", Qualifier="7",
                          Payload=b'{"smoke": true}')
        if resp["StatusCode"] != 200 or "FunctionError" in resp:
            status = "Failed"
    except Exception:
        status = "Failed"

    codedeploy.put_lifecycle_event_hook_execution_status(
        deploymentId=event["DeploymentId"],
        lifecycleEventHookExecutionId=event["LifecycleEventHookExecutionId"],
        status=status,
    )

Two permissions are needed. The hook function's role must allow codedeploy:PutLifecycleEventHookExecutionStatus, and the CodeDeploy service role must be allowed to invoke the hook function. Test the new version, not the alias, since the alias still points at the old code in BeforeAllowTraffic.

Take quiz
How does a validation hook report its result to CodeDeploy?
By returning HTTP 200 from API Gateway
By writing a file to S3
By calling PutLifecycleEventHookExecutionStatus
By publishing to an SNS topic
What should a BeforeAllowTraffic hook invoke to test the release?
The alias, which still serves the old version
The CodeDeploy service role
The previous version only
The new function version by its version number

38. How do you use CodeDeploy with AWS SAM?

AWS SAM wraps CodeDeploy for Lambda through the DeploymentPreference property. Add an AutoPublishAlias so every deployment publishes a version and moves the alias, and SAM creates the CodeDeploy application, deployment group and service role for you.

Resources:
  OrdersFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.handler
      Runtime: python3.12
      AutoPublishAlias: live
      DeploymentPreference:
        Type: Canary10Percent5Minutes
        Alarms:
          - !Ref OrdersErrorsAlarm
        Hooks:
          PreTraffic: !Ref PreTrafficCheckFunction
          PostTraffic: !Ref PostTrafficCheckFunction

The Type accepts the same canary, linear and all-at-once names. Alarms trigger rollback, and the hooks map to BeforeAllowTraffic and AfterAllowTraffic. SAM expects hook function names to start with CodeDeployHook_, which is how it scopes the permissions it grants them.

Take quiz
Which SAM property enables CodeDeploy traffic shifting for a function?
CodeUriPolicy
TrafficShiftRole
EventInvokeConfig
DeploymentPreference
Why is AutoPublishAlias required alongside DeploymentPreference?
CodeDeploy needs a published version and an alias to shift
It stores the AppSpec file
It grants the service role permissions
It sets the function timeout

39. How does file_exists_behavior work in CodeDeploy?

file_exists_behavior decides what happens when a file from your revision is already present at the destination on an EC2/on-premises instance and was not put there by a previous deployment.

Value Effect
DISALLOW (default) The deployment fails
OVERWRITE The revision's version replaces the existing file
RETAIN The existing file is kept and the revision's copy is skipped

aws deploy create-deployment ... --file-exists-behavior OVERWRITE

You can set it per deployment in the CLI or console, or at the top level of the AppSpec file. Use OVERWRITE for the first deployment onto a server with files copied by hand, and RETAIN for files such as local configuration that must survive releases.

Take quiz
What is the default behavior when a destination file already exists?
The deployment fails (DISALLOW)
The file is overwritten
The file is retained and the new one skipped
The file is renamed with a timestamp
Which value keeps an on-server configuration file untouched?
OVERWRITE
RETAIN
DISALLOW
REPLACE

40. How do tag groups select instances in a deployment group?

A deployment group can identify EC2 or on-premises instances with up to three tag groups. The matching rule has two levels.

  • Inside one tag group, an instance matches if it has any of the listed tags (OR).
  • Across tag groups, an instance must match at least one tag in every group (AND).
Goal Configuration
Instances tagged Env=prod or Env=staging One tag group with both tags
Instances that are Env=prod and Role=web Two tag groups, one tag each

Use consistent tag keys, since a typo silently removes an instance from the deployment group and it keeps running the old revision.

Take quiz
How do you target instances that have both Env=prod and Role=web?
Put both tags in a single tag group
Put each tag in its own tag group
Use two deployment configurations
Use two service roles
How are multiple tags inside a single tag group combined?
With AND, so all tags must match
Only the first tag counts
With OR, so any listed tag matches
They are ignored when an Auto Scaling group exists

41. What happens when the ApplicationStop script fails in CodeDeploy?

The deployment fails on that instance at the ApplicationStop event, and the rest of the lifecycle never runs. The subtle part is which script ran. The agent uses the ApplicationStop script from the last successfully deployed revision, not from the revision you are deploying now.

A bug in an old stop script therefore blocks every new deployment, even if the new revision already contains the fix. On the very first deployment there is no previous revision, so the event is skipped.

Ways out of the trap:

  1. Redeploy with --ignore-application-stop-failures so the failure is ignored once.
  2. Fix the cached script on the instance, then retry.
  3. Write stop scripts to be idempotent, for example tolerate an already-stopped process with || true.
aws deploy create-deployment \
  --application-name web-app --deployment-group-name prod \
  --s3-location bucket=my-bucket,key=web-app-v13.zip,bundleType=zip \
  --ignore-application-stop-failures

Take quiz
Which revision's ApplicationStop script does the agent run?
The script from the revision being deployed
The script from the oldest revision in S3
The last successfully deployed revision's script
A default script supplied by AWS
Which option lets a deployment continue past a failing ApplicationStop script?
--skip-validate-service
--force-install
--disable-hooks
--ignore-application-stop-failures

42. What happens when a deployment fails on one instance?

The outcome depends on the deployment configuration. CodeDeploy marks the failing instance as Failed and then checks whether the minimum healthy hosts rule can still be met.

Configuration Result after one instance fails
OneAtATime The deployment stops. Instances not yet reached are marked Skipped, so a bad revision touches only one host.
HalfAtATime Continues if at least half the fleet is still healthy; otherwise stops with a health constraints error.
AllAtOnce All instances were already in progress; the deployment succeeds if at least one instance succeeded.

In-place updates are not atomic, so the failed instance may be left with a partly installed revision. Automatic rollback redeploys the last good revision, while --update-outdated-instances-only lets a retry target only the instances that are not yet on the new revision.

Take quiz
With OneAtATime, what happens to instances after the one that failed?
They are updated anyway
They are rolled back automatically in parallel
They are terminated
They are skipped and the deployment stops
Which configuration can report success even if only one instance updated correctly?
AllAtOnce
OneAtATime on a single-instance fleet with 100 percent healthy
HalfAtATime with a 90 percent minimum
None of the predefined ones

43. How do you troubleshoot a failed CodeDeploy deployment?

Work from the outside in: error code first, then the agent, then scripts.

  1. Open the deployment in the console and read the error code and message on the failed event.
  2. Confirm the agent is running: sudo service codedeploy-agent status.
  3. Read codedeploy-agent.log and the deployment's scripts.log for the real script error.
  4. Check the instance profile and S3 bucket policy if the revision download returns 403.
  5. Check that appspec.yml is at the bundle root and is valid YAML.
  6. Check disk space, since the agent keeps several old revisions.
Symptom Likely cause
bad interpreter or script not found Windows CRLF line endings in a shell script
Permission denied Script not executable; set a mode in the permissions section or run chmod +x before zipping
ScriptTimedOut Hook slower than its timeout value
No instances found Tag mismatch or agent not running

Take quiz
A bash hook fails with 'bad interpreter'. What is the most likely cause?
Windows CRLF line endings in the script
A missing IAM permission
An expired load balancer certificate
A full S3 bucket
Where do you find the actual output of a failing hook script?
The S3 bucket access log
scripts.log for that deployment on the instance
CloudTrail data events
The Auto Scaling activity history

44. How do you troubleshoot the HEALTH_CONSTRAINTS error in CodeDeploy?

The message reads roughly: the overall deployment failed because too many individual instances failed, too few healthy instances were available, or some instances are experiencing problems. It means CodeDeploy could not honor the minimum healthy hosts rule.

HEALTH_CONSTRAINTS usually means too many instances failed and the threshold was crossed. HEALTH_CONSTRAINTS_INVALID means the requirement could not be met at all, for example the configuration needs more healthy hosts than the group can keep.

  1. List instance statuses with aws deploy list-deployment-instances and inspect the failed ones first.
  2. Fix the underlying hook failure on those instances; one bad script often fails the whole batch.
  3. Check for instances that were already unhealthy before the deployment started, because they count against the minimum.
  4. Review the minimum healthy hosts value. A fleet of three with a 70 percent minimum can only update one host at a time.
  5. Add capacity or lower the threshold only after the root cause is fixed.
Take quiz
What does the HEALTH_CONSTRAINTS failure indicate?
The AppSpec version is wrong
CodeDeploy could not keep the required minimum of healthy hosts
The S3 bucket policy denies the agent
The service role trust policy is missing
A fleet of 3 instances has a 70 percent minimum healthy hosts rule. How many can be updated at once?
2
3
1
0

45. How do you secure AWS CodeDeploy deployments?

Security for CodeDeploy is mostly about who can start a deployment, who can read the revision, and what the scripts can do.

  • Least privilege on the instance profile. Limit S3 read access to the revision bucket and prefix, and add kms:Decrypt if the bucket uses SSE-KMS.
  • Protect the revision bucket. Enable versioning, block public access and restrict write access, because whoever can write a revision can run code as root on your servers.
  • Limit deployment permissions. Scope codedeploy:CreateDeployment to specific applications and groups, and require approvals before production.
  • Keep secrets out of bundles. Read them at run time from Secrets Manager or Parameter Store.
  • Run scripts with the right user. Use runas rather than defaulting to root where possible.
  • Harden the network path. Use VPC interface endpoints for private subnets, and enforce IMDSv2 on instances.
  • Audit. CloudTrail records CodeDeploy API calls and EventBridge can alert on unexpected deployments.
Take quiz
Why is write access to the revision bucket sensitive?
It allows editing CloudWatch alarms
It changes the load balancer listener rules
A writer can get their own scripts executed on the servers during deployment
It lets them delete the service role
Where should application secrets be kept instead of the revision bundle?
In appspec.yml comments
In the S3 object key name
In the deployment description
In Secrets Manager or Parameter Store, read at run time

46. How does the CodeDeploy agent communicate with the service?

The agent is pull-based. It polls CodeDeploy over HTTPS (port 443) for commands, so the instance needs no inbound ports and CodeDeploy never logs in to it.

sequenceDiagram
  participant A as CodeDeploy agent
  participant C as CodeDeploy service
  participant S as S3 or GitHub
  A->>C: PollHostCommand
  C-->>A: Command for deployment
  A->>C: PutHostCommandAcknowledgement
  A->>S: Download revision
  A->>A: Run lifecycle hooks
  A->>C: PutHostCommandComplete

Instance credentials from the instance profile sign these calls. In a private subnet with no internet route, create the interface VPC endpoints com.amazonaws.<region>.codedeploy-commands-secure and, for API calls, com.amazonaws.<region>.codedeploy, plus S3 access for the revision download.

Since the agent starts every connection, the firewall only needs outbound 443. If polling fails, for example because of a proxy, the instance never picks up its command and the deployment stalls on that host. Set :proxy_uri: in codedeployagent.yml when a proxy is required.

Take quiz
How does the agent learn that there is work to do?
CodeDeploy opens an SSH session to the instance
CodeDeploy pushes files through port 22
An SNS message wakes the agent
It polls the CodeDeploy service over HTTPS
What must a private subnet have for the agent to reach CodeDeploy without internet access?
Interface VPC endpoints for CodeDeploy, plus S3 access
A public IP on the load balancer
An inbound rule for port 443
A second agent in a public subnet

47. How does CodeDeploy handle Auto Scaling scale-out during a deployment?

When Auto Scaling launches an instance in the middle of a deployment, the new instance is given the last successful revision, not the revision that is being deployed. It can therefore end up outdated while the deployment group reports success.

The deployment group setting outdatedInstancesStrategy controls the follow-up:

  • UPDATE - CodeDeploy starts a follow-on deployment to bring the new instances to the latest revision.
  • IGNORE (default) - the outdated instances are left as they are until the next deployment.
aws deploy update-deployment-group \
  --application-name web-app --current-deployment-group-name prod \
  --outdated-instances-strategy UPDATE

You can also run a deployment with --update-outdated-instances-only to touch only instances that are not on the target revision. Avoid large scaling events during a release where possible.

Take quiz
Which revision does an instance launched mid-deployment receive?
The last successful revision
The revision currently being deployed
The oldest revision in S3
No revision until a manual trigger
Which strategy makes CodeDeploy fix outdated instances with a follow-on deployment?
IGNORE
UPDATE
ROLLBACK
RETAIN

48. Explain the execution flow of a CodePipeline deployment to CodeDeploy?

CodePipeline hands the output of earlier stages to CodeDeploy as the revision, then waits for the deployment result.

flowchart LR
  A["Source stage"] --> B["Build stage: CodeBuild creates zip with appspec.yml"]
  B --> C["Optional manual approval"]
  C --> D["Deploy stage: CodeDeploy action"]
  D --> E["CodeDeploy runs deployment group"]
  E --> F["Result returned to pipeline"]
  1. A commit starts the pipeline and the source artifact is stored in the pipeline's S3 bucket.
  2. CodeBuild builds and produces an artifact that contains appspec.yml and scripts at the root.
  3. The deploy action is configured with an application name and deployment group, then calls CreateDeployment with the artifact.
  4. CodeDeploy runs the deployment, and its success or failure becomes the stage result.

For ECS blue/green the deploy action is Amazon ECS (Blue/Green). It takes taskdef.json and appspec.yaml as inputs and replaces an image placeholder such as <IMAGE1_NAME> with the new image. The pipeline's role needs CodeDeploy permissions such as codedeploy:CreateDeployment.

Take quiz
What must the CodeBuild output artifact contain for an EC2 CodeDeploy stage?
Only a Dockerfile
appspec.yml at its root along with the application files
A CloudFormation template
The deployment group ARN
What does the Amazon ECS (Blue/Green) deploy action take as inputs?
A Helm chart
Only a container image tag
taskdef.json and appspec.yaml
An EC2 launch template

49. How do you define CodeDeploy resources using CloudFormation?

CloudFormation has two resource types for this: AWS::CodeDeploy::Application and AWS::CodeDeploy::DeploymentGroup. The application sets the compute platform (Server, Lambda or ECS), and the deployment group holds targets and safety settings.

Resources:
  App:
    Type: AWS::CodeDeploy::Application
    Properties:
      ApplicationName: web-app
      ComputePlatform: Server

  ProdGroup:
    Type: AWS::CodeDeploy::DeploymentGroup
    Properties:
      ApplicationName: !Ref App
      DeploymentGroupName: prod
      ServiceRoleArn: !GetAtt CodeDeployRole.Arn
      DeploymentConfigName: CodeDeployDefault.HalfAtATime
      AutoScalingGroups:
        - !Ref WebAsg
      AutoRollbackConfiguration:
        Enabled: true
        Events:
          - DEPLOYMENT_FAILURE
          - DEPLOYMENT_STOP_ON_ALARM
      AlarmConfiguration:
        Enabled: true
        Alarms:
          - Name: !Ref Http5xxAlarm

CloudFormation only creates these objects. The revision is still deployed by CodeDeploy itself. For ECS blue/green releases driven by CloudFormation, the AWS::CodeDeployBlueGreen transform lets a stack update trigger a CodeDeploy blue/green deployment.

Take quiz
Which ComputePlatform value is used for EC2 and on-premises applications?
EC2
Instance
Server
Compute
What does CloudFormation create in this setup?
The revision bundle in S3
The CodeDeploy agent on each instance
The AppSpec file contents
The application and deployment group, not the revision deployment itself

50. How can you optimize CodeDeploy deployment time?

Most of the time in an EC2 deployment goes to batch size, load balancer draining and slow scripts, not to CodeDeploy itself.

  • Use a larger batch. Move from OneAtATime to HalfAtATime or a custom percentage once alarms and rollback protect you.
  • Shorten the deregistration delay. A 300-second default is paid for every instance and every batch.
  • Keep the bundle small. Exclude tests and build caches, and download dependencies from a nearby mirror.
  • Bake heavy setup into the AMI. Runtimes, packages and OS patches belong in the image, not in BeforeInstall.
  • Make hooks fast. Replace fixed sleep calls with a health check loop that exits early.
  • Choose blue/green where it fits. The replacement environment is built while the old one still serves traffic.
  • Clean old revisions. The agent keeps a limited number of archives, so check disk on small volumes.

Measure first. The deployment events in the console show how long each lifecycle event took, so the slowest one tells you where to spend the effort.

Take quiz
Which change removes per-instance waiting caused by connection draining?
Increasing the bundle size
Renaming the deployment group
Adding a second service role
Lowering the target group deregistration delay
Where should heavy, rarely changing setup such as runtimes and OS packages live?
In the AMI instead of a BeforeInstall hook
In the ValidateService hook
In the S3 bucket policy
In the deployment description
«
»

Comments & Discussions