DVA-C02Chapter 14 of 101Objective 3.4

CodeDeploy and CodePipeline

This chapter covers AWS CodeDeploy and CodePipeline, two core services for continuous delivery and automation of deployments. For the DVA-C02 exam, these topics fall under Domain 3: Deployment (Objective 3.4: Automate deployment using AWS CI/CD services). Approximately 15-20% of exam questions touch on CI/CD concepts, with CodeDeploy and CodePipeline appearing in 4-6 questions. You must understand the mechanics of deployment configurations, lifecycle hooks, and pipeline stage transitions to pass.

25 min read
Intermediate
Updated May 31, 2026

CodeDeploy and CodePipeline: The Assembly Line and Robot

Imagine a car factory where each car must go through a series of stations: frame welding, painting, engine installation, and final inspection. CodePipeline is the assembly line that moves the car (code) from one station to the next in a fixed order. Each station is a stage (Source, Build, Test, Deploy). CodeDeploy is the robot at the final station that actually installs the engine (deploys the code) onto the car (target environment). The robot can be programmed to install engines on multiple identical cars simultaneously (rolling deployment), or to install one engine, test it, then install on the next (blue/green). The assembly line has a conveyor belt that only moves when the previous station signals completion. If the robot fails to install an engine, the assembly line can automatically stop (rollback) and send the car back to a previous station. The factory manager (CloudWatch Events) watches the entire line and can send alerts if a station is taking too long (timeout) or if the robot is jammed (deployment failure). This analogy maps directly: CodePipeline orchestrates the sequential stages, while CodeDeploy performs the actual deployment actions on instances, Lambda functions, or ECS services.

How It Actually Works

What is AWS CodeDeploy?

AWS CodeDeploy is a fully managed deployment service that automates code deployments to any instance, including Amazon EC2, on-premises servers, AWS Lambda functions, and Amazon ECS services. It handles the complexity of updating applications with minimal downtime, supports rolling and blue/green deployments, and integrates with CodePipeline for CI/CD.

Why CodeDeploy Exists

Before CodeDeploy, engineers had to manually script deployment processes using SSH, custom scripts, or configuration management tools like Chef/Puppet. These scripts were brittle, lacked rollback capabilities, and did not provide a unified view of deployment status across fleets. CodeDeploy provides a standardized, repeatable, and auditable mechanism that works across environments.

How CodeDeploy Works Internally

CodeDeploy uses a revision – a combination of an application specification file (appspec.yml) and the application files (source code, scripts). The appspec.yml defines: - files: which files to copy from the revision to the instance. - hooks: lifecycle event hooks where you run scripts (e.g., before install, after install). - permissions: file permissions.

The deployment process on EC2/on-premises: 1. Agent: CodeDeploy agent runs on the target instance, polling the CodeDeploy service for work. 2. Revision download: Agent downloads the revision from Amazon S3 or GitHub. 3. Lifecycle events: Agent executes hooks in order: BeforeBlockTraffic, BlockTraffic, AfterBlockTraffic, ApplicationStop, DownloadBundle, BeforeInstall, Install, AfterInstall, ApplicationStart, ValidateService, BeforeAllowTraffic, AllowTraffic, AfterAllowTraffic. 4. Success/Failure: Agent reports status back to CodeDeploy service. On failure, the deployment can be configured to roll back.

Key Components, Values, Defaults, and Timers

- Deployment Group: A set of instances (EC2 tags, ASG names) or Lambda functions targeted for deployment. - Deployment Config: Defines deployment speed and failure thresholds. - OneAtATime: Deploys to one instance at a time, waits for success before next. - HalfAtATime: Deploys to 50% of instances. - AllAtOnce: Deploys to all instances simultaneously. - Canary and Linear (for Lambda/ECS): Traffic shifting. - Default timeout for lifecycle hooks: 3600 seconds (1 hour). - Revision location: S3 bucket or GitHub repository. S3 bucket must have versioning enabled. - Agent polling interval: Every 1 second by default. - Maximum number of concurrent deployments per deployment group: 1 (default, but can be increased).

CodeDeploy for Lambda and ECS

For Lambda, CodeDeploy manages traffic shifting between versions using Canary or Linear configurations. For example, a canary configuration Canary10Percent5Minutes shifts 10% of traffic to the new version for 5 minutes, then shifts the remaining 90%. For ECS, CodeDeploy works with the ECS service to perform blue/green deployments using Application Load Balancer target groups.

Verification Commands

aws deploy create-application --application-name MyApp

aws deploy create-deployment-group --application-name MyApp --deployment-group-name MyDG --service-role-arn arn:aws:iam::123456789012:role/CodeDeployRole --ec2-tag-filters Key=Name,Value=MyInstance,Type=KEY_AND_VALUE

aws deploy create-deployment --application-name MyApp --deployment-group-name MyDG --s3-location bucket=my-bucket,key=my-revision.zip,bundleType=zip

aws deploy list-deployments --application-name MyApp --deployment-group-name MyDG

What is AWS CodePipeline?

CodePipeline is a fully managed continuous delivery service that orchestrates the build, test, and deploy phases of your release process. It models the release pipeline as a series of stages (e.g., Source, Build, Test, Deploy), each containing actions that are executed sequentially or in parallel.

How CodePipeline Works Internally

1.

Pipeline Structure: A pipeline is a workflow definition. Each stage contains one or more action groups. Actions within a stage can run in parallel if they are in different action groups.

2.

Artifacts: Outputs from stages are stored as artifacts in an S3 bucket (the artifact store). Artifacts are passed to subsequent stages.

3.

Transitions: After a stage completes successfully, the pipeline transitions to the next stage automatically (or manually if configured).

4.

Execution: Each time the pipeline is triggered (by a change in source, manual invocation, or schedule), a new execution starts. Executions run sequentially per pipeline.

5.

Action Providers: CodePipeline integrates with many AWS services (CodeCommit, S3, CodeBuild, CodeDeploy, Elastic Beanstalk, CloudFormation, Lambda, ECS, etc.) and third-party tools (GitHub, Jenkins, TeamCity).

Key Values and Defaults

Artifact store: Default is an S3 bucket managed by AWS (or you can specify a custom bucket).

Maximum number of stages: 10 (can be increased via support request).

Maximum number of actions per stage: 20.

Execution timeout: 7 days (maximum time a pipeline execution can run).

Polling interval for source actions: Every 1 minute for CodeCommit, S3, ECR.

Webhook-based triggers: For GitHub, CodePipeline uses webhooks to start automatically.

How CodePipeline Interacts with CodeDeploy

CodePipeline often includes a Deploy stage that uses CodeDeploy as the action provider. The pipeline passes the deployment artifact (e.g., a ZIP file) to CodeDeploy. CodeDeploy then deploys that artifact to the instances or Lambda functions defined in the deployment group. The pipeline waits for the CodeDeploy deployment to succeed or fail before proceeding.

Example Pipeline Configuration

# sample-pipeline.yaml
pipeline:
  name: MyPipeline
  stages:
    - name: Source
      actions:
        - name: SourceAction
          actionTypeId:
            category: Source
            owner: AWS
            provider: CodeCommit
            version: 1
          configuration:
            RepositoryName: MyRepo
            BranchName: main
          outputArtifacts:
            - name: SourceArtifact
    - name: Build
      actions:
        - name: BuildAction
          actionTypeId:
            category: Build
            owner: AWS
            provider: CodeBuild
            version: 1
          configuration:
            ProjectName: MyBuildProject
          inputArtifacts:
            - name: SourceArtifact
          outputArtifacts:
            - name: BuildArtifact
    - name: Deploy
      actions:
        - name: DeployAction
          actionTypeId:
            category: Deploy
            owner: AWS
            provider: CodeDeploy
            version: 1
          configuration:
            ApplicationName: MyApp
            DeploymentGroupName: MyDG
          inputArtifacts:
            - name: BuildArtifact

Verification Commands

aws codepipeline create-pipeline --cli-input-json file://pipeline.json

aws codepipeline list-pipelines

aws codepipeline start-pipeline-execution --name MyPipeline

aws codepipeline get-pipeline-state --name MyPipeline

Common Pitfalls

IAM permissions: The CodeDeploy service role must have permissions to read from S3 and describe EC2 instances. The CodePipeline service role must have permissions to invoke CodeDeploy and read artifacts.

Agent not running: On EC2, if the CodeDeploy agent is not installed or not running, deployments hang and eventually fail.

Revision format: The appspec.yml must be at the root of the revision for EC2/on-premises. For Lambda, the appspec.yml must be included in the revision.

Cross-account deployments: CodeDeploy can deploy to instances in a different account using cross-account roles.

Walk-Through

1

Create Application and Deployment Group

First, create a CodeDeploy application (e.g., MyApp) and a deployment group (e.g., MyDG). The deployment group identifies the target instances using EC2 tags, Auto Scaling groups, or for Lambda, the function name. You also specify the service role ARN that grants CodeDeploy permissions to interact with EC2, ASG, and S3. The deployment configuration (e.g., AllAtOnce) is chosen here. This step is done via AWS Console, CLI, or CloudFormation.

2

Prepare Revision and Push to S3

Create a revision: a ZIP or tar.gz file containing the application source code and an appspec.yml file at the root. Upload this revision to an S3 bucket with versioning enabled. The bucket must be in the same region as the CodeDeploy application. You can also use GitHub as a revision location, but S3 is more common for automated pipelines. The revision is identified by its bucket, key, and bundle type.

3

Create Deployment

Call the CreateDeployment API via CLI or SDK. Specify the application name, deployment group name, and revision location (S3 or GitHub). CodeDeploy then instructs the agent on each target instance to download and apply the revision. The deployment is assigned a unique ID. You can monitor progress using the console or CLI commands like `aws deploy get-deployment`.

4

Agent Downloads and Executes Lifecycle Hooks

On each instance, the CodeDeploy agent polls the service and receives the deployment instruction. It downloads the revision from S3 to a temporary directory. Then it executes lifecycle event hooks in order: ApplicationStop (stop existing app), DownloadBundle, BeforeInstall, Install (copies files), AfterInstall, ApplicationStart, ValidateService. Each hook runs a script you specify. If any hook fails (non-zero exit code), the deployment fails for that instance.

5

Traffic Shifting (Blue/Green or Canary)

For blue/green deployments on EC2 or ECS, after the new instances are healthy, CodeDeploy shifts traffic from the old (blue) to the new (green) environment. The shift can be immediate (AllAtOnce) or gradual (Linear or Canary). For Lambda, traffic shifting between versions is controlled by the deployment configuration. The old environment remains until the deployment succeeds or is rolled back.

6

Rollback on Failure

If the deployment fails (e.g., ValidateService hook returns error, or instance becomes unhealthy), CodeDeploy can automatically roll back to the last known good revision. Rollback is configured in the deployment group. During rollback, the agent re-deploys the previous revision. For blue/green, traffic is shifted back to the old environment. CloudWatch Events can trigger notifications on failure.

What This Looks Like on the Job

Enterprise Scenario 1: E-Commerce Platform with Blue/Green Deployments

A large e-commerce company uses CodeDeploy to deploy microservices on ECS Fargate. They have a pipeline that builds Docker images, pushes them to ECR, and then uses CodeDeploy to perform blue/green deployments with a linear traffic shift (10% every 10 minutes). This allows them to monitor error rates and latency during the shift. If the new version causes a spike in 5xx errors, CloudWatch Alarms trigger a rollback. They configure the deployment group with a minimum healthy percentage of 50% to ensure capacity. The pipeline runs multiple times per day, and CodeDeploy manages the traffic routing via the ALB target groups. A misconfiguration of the appspec.yml (e.g., wrong container name) can cause the deployment to fail, but the automatic rollback restores the previous version within minutes.

Enterprise Scenario 2: Financial Services with Compliance Audits

A bank uses CodePipeline and CodeDeploy to deploy to EC2 instances behind an Auto Scaling group. They need to ensure that every deployment is audited. They enable S3 bucket versioning for the artifact store and use AWS CloudTrail to log all API calls. The pipeline includes an approval stage before production deployment. CodeDeploy's lifecycle hooks run security scans (e.g., antivirus, SAST) in the BeforeInstall hook. If a scan fails, the hook returns a non-zero exit code, stopping the deployment. The bank also uses CodeDeploy's deployment history to prove that only approved revisions were deployed. A common issue is that the CodeDeploy agent on spot instances may be terminated, causing incomplete deployments. They mitigate this by using lifecycle hooks in the ASG to gracefully handle instance termination.

Enterprise Scenario 3: SaaS Provider with Canary Deployments for Lambda

A SaaS provider uses CodeDeploy to manage canary deployments for AWS Lambda functions. They have a pipeline that builds the Lambda zip, publishes a new version, and updates the alias to point to the new version. They use a canary deployment configuration Canary10Percent5Minutes to shift 10% of traffic for 5 minutes. During this time, they monitor invocation errors and duration. If the error rate exceeds 1%, they manually roll back by updating the alias to the old version. A common mistake is forgetting to include the appspec.yml in the revision; for Lambda, the appspec.yml must be present in the revision root. Another issue is that the Lambda function's reserved concurrency can cause throttling during the canary if not adjusted.

How DVA-C02 Actually Tests This

Exactly What DVA-C02 Tests

DVA-C02 tests your ability to:

Design a CI/CD pipeline using CodePipeline with stages like Source, Build, Test, Deploy.

Choose the correct CodeDeploy deployment configuration (AllAtOnce, OneAtATime, HalfAtATime, Canary, Linear) based on requirements for speed vs. safety.

Understand lifecycle hooks and their order (especially BeforeAllowTraffic and AfterAllowTraffic for blue/green).

Identify reasons for deployment failure: agent not running, wrong IAM permissions, appspec.yml malformed, hook script fails.

Use CodeDeploy with Lambda and ECS (blue/green and canary).

Integrate CodePipeline with other services: CodeCommit, CodeBuild, CloudFormation, Elastic Beanstalk.

Common Wrong Answers and Why

1.

"Use CodeDeploy to compile source code" – CodeDeploy does not compile; it deploys pre-compiled artifacts. CodeBuild is for building.

2.

"CodePipeline can deploy directly to EC2 without CodeDeploy" – CodePipeline cannot directly deploy to EC2; it uses CodeDeploy, Elastic Beanstalk, CloudFormation, or ECS as deploy actions.

3.

"CodeDeploy supports only EC2 instances" – Wrong; it supports on-premises, Lambda, and ECS.

4.

"The appspec.yml must be in JSON format" – It can be YAML or JSON; YAML is more common.

5.

"Blue/green deployments are only for EC2" – Available for Lambda and ECS as well.

Specific Numbers and Terms on the Exam

Lifecycle hook order: BeforeBlockTraffic, BlockTraffic, AfterBlockTraffic, ApplicationStop, DownloadBundle, BeforeInstall, Install, AfterInstall, ApplicationStart, ValidateService, BeforeAllowTraffic, AllowTraffic, AfterAllowTraffic.

Deployment configs: Canary10Percent5Minutes, Canary10Percent15Minutes, Linear10PercentEvery1Minute, Linear10PercentEvery3Minutes, AllAtOnce, OneAtATime, HalfAtATime.

Timeout: Default 1 hour for lifecycle hooks.

Artifact store: S3 bucket managed by CodePipeline (default) or customer-managed.

Maximum pipeline stages: 10.

Edge Cases and Exceptions

Deploying to an empty deployment group: The deployment will succeed immediately with no instances.

Rollback: If the deployment group has automatic rollback enabled, CodeDeploy will roll back on any failure, including a timeout.

Cross-region actions: CodePipeline supports cross-region actions, but the artifact store must be in the same region as the action.

Manual approval: Use a manual approval action in CodePipeline; it pauses the pipeline until approved.

How to Eliminate Wrong Answers

If the question mentions building code, eliminate CodeDeploy and consider CodeBuild.

If the question requires orchestrating multiple stages, choose CodePipeline.

If the question involves traffic shifting percentages, look for CodeDeploy deployment configuration names.

If the question asks about running scripts before deployment, think about lifecycle hooks in appspec.yml.

If the question involves rolling back to a previous version, CodeDeploy's automatic rollback is the answer.

Key Takeaways

CodePipeline orchestrates stages (Source, Build, Test, Deploy); CodeDeploy performs the actual deployment.

CodeDeploy supports EC2, on-premises, Lambda, and ECS – each with a specific appspec.yml format.

Lifecycle hooks run in a fixed order; ValidateService is the last hook before traffic is allowed.

Deployment configurations: AllAtOnce, OneAtATime, HalfAtATime for EC2; Canary and Linear for Lambda/ECS.

CodeDeploy agent must be installed on EC2 instances; it polls every 1 second.

CodePipeline artifact store is an S3 bucket; artifacts are passed between stages.

Automatic rollback can be enabled in CodeDeploy to revert to the last successful deployment.

Blue/green deployments create a new environment and shift traffic; old environment remains for rollback.

CodePipeline supports manual approval actions to pause the pipeline.

Common failure causes: agent not running, wrong IAM permissions, malformed appspec.yml, hook script errors.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

CodeDeploy

Deploys to existing EC2 instances, on-premises, Lambda, or ECS.

Requires manual setup of deployment groups and agent.

Supports blue/green and rolling deployments with fine-grained control.

Lifecycle hooks allow custom scripts at each step.

Integrates with CodePipeline for CI/CD.

Elastic Beanstalk

Manages entire environment (EC2, ASG, ELB, RDS) as a single unit.

Automatically provisions resources and handles capacity.

Supports rolling and immutable deployments (blue/green) but less configurable.

Customization via .ebextensions and platform hooks.

Can be a deployment target in CodePipeline but is more opinionated.

Watch Out for These

Mistake

CodeDeploy can only deploy to EC2 instances.

Correct

CodeDeploy supports EC2, on-premises instances, AWS Lambda functions, and Amazon ECS services. Each has its own deployment mechanisms and appspec.yml format.

Mistake

CodePipeline requires CodeCommit as the source.

Correct

CodePipeline supports multiple source providers: CodeCommit, S3, ECR, GitHub, and Bitbucket. You can also use third-party sources via webhooks.

Mistake

CodeDeploy automatically installs the agent on EC2 instances.

Correct

The CodeDeploy agent must be manually installed and started on each EC2 instance (or via user data/AMI). The agent polls the CodeDeploy service for deployment instructions.

Mistake

Blue/green deployments replace all instances at once.

Correct

Blue/green deployments create a new set of instances (green) alongside the old (blue). Traffic is shifted gradually or all at once, but the old instances remain until the deployment succeeds or is rolled back.

Mistake

CodePipeline can deploy directly to EC2 without any additional service.

Correct

CodePipeline's Deploy stage must use a deploy provider like CodeDeploy, Elastic Beanstalk, CloudFormation, or ECS. It cannot directly SSH into EC2 instances.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

What is the difference between CodeDeploy and CodePipeline?

CodePipeline is a CI/CD orchestration service that manages the sequence of stages (source, build, test, deploy). CodeDeploy is a deployment service that handles the actual deployment of code to instances or serverless resources. CodePipeline can use CodeDeploy as a deploy action provider. Think of CodePipeline as the conductor and CodeDeploy as the musician.

How do I set up a blue/green deployment with CodeDeploy?

For EC2, create a deployment group with a blue/green deployment configuration. CodeDeploy launches new instances (green) based on a launch template or Auto Scaling group. Traffic is shifted using an Elastic Load Balancer. For ECS, CodeDeploy works with ECS service and ALB target groups. For Lambda, you use a canary or linear configuration to shift traffic between versions.

What is the appspec.yml file and where should it be placed?

The appspec.yml is a YAML (or JSON) file that defines the deployment instructions: files to copy, permissions, and lifecycle hooks. For EC2/on-premises, it must be at the root of the revision archive. For Lambda, it must also be at the root. For ECS, it specifies the task definition and container details.

How do I troubleshoot a failed CodeDeploy deployment?

Check the deployment events in the CodeDeploy console or CLI. Look at the lifecycle hook logs on the instance (under /opt/codedeploy-agent/deployment-root/deployment-group-id/deployment-id/logs/). Common issues: agent not running, IAM role missing permissions, hook script returning non-zero exit code, or revision not accessible from S3.

Can CodePipeline deploy to multiple environments (dev, test, prod)?

Yes. You can create multiple stages in the pipeline, each with a deploy action targeting a different deployment group or environment. You can also use manual approval actions between stages to control promotion. For example: Source > Build > Deploy to Dev > Approve > Deploy to Prod.

What is the default timeout for a CodeDeploy lifecycle hook?

The default timeout for each lifecycle hook is 3600 seconds (1 hour). You can override this in the appspec.yml by specifying a timeout value in seconds for each hook. If the hook script does not complete within the timeout, the deployment fails.

How does CodePipeline handle artifacts?

Each action in a pipeline can produce output artifacts, which are stored in an S3 bucket (the artifact store). Subsequent actions can consume these artifacts as input. The artifact store is automatically created by CodePipeline in the same region, or you can specify a custom bucket. Artifacts are typically ZIP files.

Terms Worth Knowing

Ready to put this to the test?

You've just covered CodeDeploy and CodePipeline — now see how well it sticks with free DVA-C02 practice questions. Full explanations included, no account needed.

Done with this chapter?