AWS CodeBuild
Overview
AWS CodeBuild is a fully managed build service. It compiles code, runs tests and produces artifacts inside a fresh container for every build, and you pay per build minute with nothing to patch or scale. Each build is described by a buildspec.yml file kept next to the source.
Imagine a hotel that gives every guest a freshly cleaned room: no leftovers from the previous guest, and as many rooms as guests arrive. CodeBuild gives every commit a clean environment and runs many builds in parallel, so there is no build queue as with a shared Jenkins server.
On the exam CodeBuild shows up in questions about buildspec phases, caching, running inside a VPC, building Docker images, handling secrets, test reports and troubleshooting failed builds.
Key Concepts
- The buildspec.yml defines phases: install, pre_build, build, post_build, plus artifacts, cache, env and reports sections.
- A build runs in a managed Docker image (curated or custom from ECR) on a chosen compute type; also available are Lambda compute, ARM and GPU fleets and reserved-capacity fleets.
- Privileged mode must be enabled to run the Docker daemon (build images inside CodeBuild).
- Caching: S3 cache or local cache (source, Docker layer, custom) speeds up dependencies.
- Secrets come from env parameter-store / secrets-manager mappings, never plain environment variables.
- Run builds inside your VPC to reach private resources; needs NAT or endpoints for internet and AWS APIs.
- Test reports (JUnit, Cucumber, etc.) and code coverage reports appear in the console and can gate pipelines.
- Batch builds run build graphs, lists or matrices in parallel from one request.
Detailed Notes
A complete buildspec
version: 0.2
env:
variables:
APP_ENV: ci
parameter-store:
NPM_TOKEN: /ci/npm-token
secrets-manager:
DB_PASS: ci/db:password
phases:
install:
runtime-versions:
nodejs: 20
commands:
- npm ci
pre_build:
commands:
- aws ecr get-login-password | docker login --username AWS --password-stdin $ECR_URI
build:
commands:
- npm test -- --ci
- docker build -t $ECR_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION .
post_build:
commands:
- docker push $ECR_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION
- printf '[{"name":"web","imageUri":"%s"}]' $ECR_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION > imagedefinitions.json
reports:
unit:
files: ["junit.xml"]
file-format: JUNITXML
artifacts:
files: [imagedefinitions.json]
cache:
paths: [node_modules/**/*]
Phase behaviour
| Phase | Purpose | Failure effect |
|---|---|---|
| install | Install runtimes and tools | Build fails |
| pre_build | Login, restore deps, run linters | Build fails |
| build | Compile and test | Build fails; post_build still runs |
| post_build | Push images, notify, package | Runs after build regardless of success (check CODEBUILD_BUILD_SUCCEEDING) |
Add on-failure: CONTINUE to a phase to keep going, and use finally blocks for cleanup.
Environment, caching and networking
- Cache types: Amazon S3 (shared across fleet) and local (source, Docker layer, custom; fastest but best-effort on the same host).
- VPC access: supply VPC, subnets and security groups. Builds in private subnets need a NAT gateway or VPC endpoints (S3, ECR, CloudWatch Logs) to download dependencies.
- Service role: must allow logs, S3 artifacts, ECR push and any secrets read. Use a separate role per project for least privilege.
- Environment variables types: PLAINTEXT, PARAMETER_STORE, SECRETS_MANAGER. Parameter Store names must exist and be readable by the service role.
Docker builds
# Build a multi-architecture image with buildx inside CodeBuild (privileged mode on)
docker buildx build --platform linux/amd64,linux/arm64 -t $ECR_URI:latest --push .
Docker Hub rate limits can fail builds; authenticate or use ECR pull-through cache for base images.
Batch and parallel builds
version: 0.2
batch:
fast-fail: true
build-matrix:
static:
ignore-failure: false
dynamic:
env:
variables:
NODE_VER: ["18", "20", "22"]
Reports and quality gates
Test reports record pass/fail counts and trends; code-coverage reports show line and branch coverage. A CodePipeline stage fails when the build fails, so convert gates (coverage below 80%) into a non-zero exit code in the build phase.
Troubleshooting
| Symptom | Likely cause |
|---|---|
Cannot connect to the Docker daemon | Privileged mode disabled |
| Timeout downloading packages in VPC build | No NAT gateway / endpoints |
AccessDenied pulling from ECR | Service role missing ecr:GetAuthorizationToken or pull permissions |
| Artifact missing | Wrong files path or base-directory |
| Parameter not found | Wrong path or role lacks ssm:GetParameters |
Use CodeBuild local agent to test buildspec files on a workstation, and session manager debugging (codebuild-breakpoint command) to inspect a failing build.
Build performance, reports and common failures
| Topic | Guidance |
|---|---|
| Compute | Choose small, medium, large or reserved capacity fleets (and Lambda compute) by build duration and memory; ARM builds for Graviton images |
| Caching | S3 cache for dependencies, local cache (docker layer, source, custom) for repeat builds on the same host |
| Test reports | Declare a reports section so JUnit/Cucumber results and code coverage appear in the console and can gate the pipeline |
| Batch builds | Fan out matrix builds (build-matrix, build-graph, build-list) and aggregate artifacts |
| Secrets | env.secrets-manager and env.parameter-store inject values at runtime without logging them |
reports:
unit-tests:
files: ["target/surefire-reports/*.xml"]
file-format: JUNITXML
The build phase succeeds or fails on the exit code of each command, which is how test failures stop a pipeline. Frequent failures: Docker rate limits when pulling base images (pull from ECR or a pull-through cache), missing privileged: true for Docker-in-Docker, the service role lacking logs:* or S3 permissions, and VPC builds without a NAT gateway or endpoints to reach the internet.
Real World Example
Scenario: a SaaS company replaces a self-managed Jenkins fleet. Jenkins agents were idle most nights and saturated at release time. The team moves to CodeBuild: each service has a buildspec, builds run inside a VPC so integration tests reach a private RDS test instance, and an S3 cache plus Docker layer caching cuts build time from 14 to 5 minutes.
Secrets are pulled from Secrets Manager via the env block, and unit-test reports gate promotion. Idle cost drops to zero and there are no agent AMIs to patch.
Architecture Diagram
Each build runs in a clean container; results go to S3, ECR and reports.
- 1CodeBuild downloads the source and starts a fresh container.
- 2install and pre_build phases prepare tools and credentials.
- 3build runs compile and tests, reaching private resources through the VPC.
- 4post_build pushes images and packages artifacts.
- 5Artifacts, logs and test reports are stored for the next pipeline stage.
Best Practices
- ✓Give each project its own least-privilege service role.
- ✓Pull secrets with parameter-store / secrets-manager env mappings, never plaintext variables.
- ✓Enable caching (local Docker layer and S3 dependency cache) to cut build time.
- ✓Emit JUnit and coverage reports and fail the build on quality thresholds.
- ✓Use VPC endpoints or NAT for VPC builds and ECR pull-through cache to avoid Docker Hub limits.
Common Interview Questions
Exam Tips
DOP-C02 focus
- Privileged mode = Docker builds; VPC config = private resource access; NAT/endpoints = internet and AWS API access.
- Secrets: parameter-store / secrets-manager in buildspec; plaintext env vars are the wrong answer.
- "Speed up repeated builds" = cache (local or S3).
- Parallel testing across versions = batch builds (build matrix).
Finished this lesson?
0 of 44 lessons done · 0% of the course

