CodeBuild, CodeDeploy and CodePipeline
Overview
A CI/CD pipeline turns every code change into a tested, deployable release automatically. AWS offers a family of developer tools: CodeBuild compiles and tests, CodeDeploy rolls out to servers, containers or Lambda, and CodePipeline connects the stages into a workflow. CodeArtifact stores packages. (Note: CodeCommit is closed to new customers since July 2024, so new projects typically use GitHub, GitLab or Bitbucket via CodeConnections.)
Think of a factory line. Source is the raw material arriving, CodeBuild is the assembly and quality test, CodeDeploy is the delivery truck that unloads at the shops one batch at a time, and CodePipeline is the conveyor with approval gates in between.
You need to read buildspec.yml and appspec.yml files, know the deployment types, and understand rollbacks.
Key Concepts
- CodePipeline orchestrates stages (Source, Build, Test, Approval, Deploy) with actions that pass artifacts through S3; it can start from GitHub (CodeConnections), S3, ECR or CodeCommit.
- CodeBuild is a managed build service that runs commands from buildspec.yml in containers; you pay per build minute and it scales without build servers.
- buildspec phases: install, pre_build, build, post_build; sections for env, artifacts, cache, reports.
- CodeDeploy deploys to EC2/on-premises, Lambda and ECS using an appspec file; it supports in-place (EC2 only) and blue/green deployments.
- EC2 appspec lifecycle hooks: ApplicationStop, BeforeInstall, AfterInstall, ApplicationStart, ValidateService (plus load balancer hooks for blue/green).
- Lambda and ECS blue/green use canary, linear or all-at-once traffic shifting with CloudWatch alarm rollback.
- The CodeDeploy agent must run on EC2 instances; instances need an instance profile with S3 access and tags/ASG to be targeted.
- Manual approval actions (with SNS notifications) gate production deployments; EventBridge reports pipeline state changes.
Detailed Notes
Build specification
version: 0.2
env:
variables:
STAGE: prod
parameter-store:
API_URL: /myapp/prod/api-url
phases:
install:
runtime-versions:
python: 3.12
pre_build:
commands:
- pip install -r requirements.txt
build:
commands:
- pytest -q
- sam build
post_build:
commands:
- echo Build finished on `date`
reports:
unit-tests:
files: ["reports/junit.xml"]
file-format: JUNITXML
artifacts:
files:
- '**/*'
base-directory: .aws-sam/build
cache:
paths:
- /root/.cache/pip/**/*
If a command fails, the phase fails and the build stops (except post_build still runs after failure of earlier phases). Secrets should come from Secrets Manager or Parameter Store via the env section, never plain variables. The CodeBuild project needs a service role (logs, S3 artifacts, ECR push) and privileged mode to build Docker images.
CodeDeploy appspec for EC2
version: 0.0
os: linux
files:
- source: /
destination: /var/www/app
hooks:
ApplicationStop:
- location: scripts/stop.sh
timeout: 60
BeforeInstall:
- location: scripts/install_deps.sh
ApplicationStart:
- location: scripts/start.sh
ValidateService:
- location: scripts/health_check.sh
timeout: 120
Deployment strategies
| Strategy | Compute | Behaviour | Rollback |
|---|---|---|---|
| In-place | EC2/on-prem | Stop, update and restart instances in batches (AllAtOnce, HalfAtATime, OneAtATime) | Redeploy previous revision |
| Blue/green | EC2 | New instances in a replacement ASG; ALB switches traffic | Reroute to original quickly |
| Canary/linear | Lambda, ECS | Shift traffic in steps | Automatic by alarm |
Lambda appspec:
version: 0.0
Resources:
- OrdersFn:
Type: AWS::Lambda::Function
Properties:
Name: OrdersFn
Alias: live
CurrentVersion: 7
TargetVersion: 8
Hooks:
- BeforeAllowTraffic: PreTrafficHookFn
- AfterAllowTraffic: PostTrafficHookFn
CodePipeline structure
Stages:
- Name: Source
Actions:
- Name: GitHub
ActionTypeId: { Category: Source, Owner: AWS, Provider: CodeStarSourceConnection, Version: "1" }
OutputArtifacts: [{ Name: SourceOut }]
- Name: Build
Actions:
- Name: Build
ActionTypeId: { Category: Build, Owner: AWS, Provider: CodeBuild, Version: "1" }
InputArtifacts: [{ Name: SourceOut }]
OutputArtifacts: [{ Name: BuildOut }]
- Name: Approve
Actions:
- Name: Manual
ActionTypeId: { Category: Approval, Owner: AWS, Provider: Manual, Version: "1" }
- Name: Deploy
Actions:
- Name: Deploy
ActionTypeId: { Category: Deploy, Owner: AWS, Provider: CloudFormation, Version: "1" }
Artifacts live in an S3 artifact store (encrypted with KMS); each action needs a role. Cross-account deployments use a cross-account role and customer-managed KMS key for artifacts.
Services summary
| Service | Purpose |
|---|---|
| CodePipeline | Orchestrate release workflow |
| CodeBuild | Build, test, package |
| CodeDeploy | Deploy to EC2, Lambda, ECS |
| CodeArtifact | Private package repositories (npm, pip, Maven) |
| CodeGuru Reviewer | Automated code review (limited availability) |
Running builds locally
aws codebuild start-build --project-name myapp-build \
--environment-variables-override name=STAGE,value=staging,type=PLAINTEXT
Troubleshooting
- CodeDeploy fails at start: agent not running or instance profile missing S3 permissions.
- Build cannot pull private packages: the CodeBuild role lacks access or the project is not in a VPC with NAT.
- Pipeline stuck: pending approval or missing role permissions on the artifact bucket/KMS key.
buildspec and appspec essentials
version: 0.2
env:
variables: { STAGE: test }
parameter-store: { DB_URL: /orders/test/db-url }
phases:
install:
runtime-versions: { python: 3.12 }
pre_build:
commands: [pip install -r requirements.txt, pytest -q]
build:
commands: [sam build, sam package --s3-bucket $ARTIFACT_BUCKET --output-template-file packaged.yaml]
reports:
unit:
files: ["reports/junit.xml"]
file-format: JUNITXML
artifacts:
files: [packaged.yaml]
cache:
paths: [/root/.cache/pip/**/*]
CodeBuild runs each phase in order and fails the build when a command returns non-zero; post_build still runs. The service role needs access to the artifact bucket and any secrets referenced by parameter-store or secrets-manager variables.
| CodeDeploy platform | Strategies | appspec content |
|---|---|---|
| EC2 / on-premises | In-place (all at once, half at a time, one at a time), blue/green | files and hooks: ApplicationStop, BeforeInstall, AfterInstall, ApplicationStart, ValidateService |
| Lambda | Canary, linear, all-at-once on aliases | Resources (alias and versions) and hooks BeforeAllowTraffic, AfterAllowTraffic |
| ECS | Blue/green with a load balancer, canary, linear | Task definition, container and port; hooks include AfterAllowTestTraffic |
CodeDeploy rolls back automatically on deployment failure or when a configured CloudWatch alarm fires; the instance agent must be installed and the instance role must read the artifact. CodePipeline stages move artifacts in S3 between actions, and an execution can be restarted from a failed stage.
Triggers and branching
Pipelines start from a Git push or tag through a CodeConnections (CodeStar) connection, or on a schedule, or from an EventBridge rule. V2 pipelines support variables, triggers on branch and tag filters, and parallel execution modes. Note that AWS CodeCommit is closed to new customers, so new projects typically use GitHub, GitLab or Bitbucket, but existing questions still reference its concepts (HTTPS Git credentials, git-remote-codecommit, IAM-based access).
Real World Example
A fintech team uses GitHub, CodePipeline and CodeBuild. A push to main triggers unit tests, a SAM build and deployment to a staging stack. After a manual approval, CodeDeploy shifts the production Lambda alias with a Canary10Percent10Minutes policy and a CloudWatch alarm for error rate. A failing pre-traffic hook stopped one release before any customer traffic moved to it.
Architecture Diagram
Source triggers build, approval gates production and CodeDeploy shifts traffic.
- 1A commit triggers the pipeline and fetches the source artifact.
- 2CodeBuild runs buildspec commands and outputs a build artifact.
- 3A reviewer approves the production stage.
- 4CodeDeploy rolls out gradually and rolls back on alarm.
Best Practices
- ✓Keep buildspec and appspec in source control with the code.
- ✓Load secrets from Secrets Manager / Parameter Store, never plain text.
- ✓Use blue/green or canary deployments with alarms for production.
- ✓Cache dependencies in CodeBuild to speed builds.
- ✓Give each pipeline stage a least-privilege role.
Common Interview Questions
Exam Tips
DVA-C02 focus
- buildspec.yml -> CodeBuild; appspec.yml -> CodeDeploy.
- In-place deployments exist only on EC2/on-premises; Lambda and ECS are blue/green style.
- Rollback on failure for Lambda/ECS -> CloudWatch alarms in the deployment group.
- CodeDeploy EC2 failures: check agent and instance profile.
Finished this lesson?
0 of 46 lessons done · 0% of the course

