Lesson 1 of 5 AWS CI/CD Services

Building and Testing Code with AWS CodeBuild

This lesson explains how AWS CodeBuild, a fully managed build service, compiles code, runs tests and produces deployable artifacts, scaling automatically with no build servers to manage.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the phases and sections of a buildspec file.
  • Identify the build environment settings that commonly cause build failures.
  • Describe how build logs, caching and test reports help diagnose and speed up builds.

The buildspec file

CodeBuild runs each build in a fresh container, using an image that provides the operating system and language runtimes, and follows the instructions in buildspec.yml at the source root, unless the project names another location.

The env section defines environment variables. Values can be plain text or fetched at build time from Parameter Store and Secrets Manager, which keeps tokens and passwords out of the buildspec and the project configuration. The phases section lists commands in four phases that always run in order: install for runtimes and tools, pre_build for steps such as signing in to ECR, build for compiling and testing, and post_build for steps such as pushing an image.

The reports section publishes test and code coverage results so they appear in the CodeBuild console. The artifacts section names the files to keep, such as a packaged template, which CodeBuild uploads to S3 or passes to the next stage of a pipeline. The cache section stores files, such as downloaded dependencies, between builds to make later builds faster. The following table summarises the sections.

SectionPurpose
envVariables, including values from Parameter Store and Secrets Manager
phasesCommands run in order: install, pre_build, build, post_build
reportsTest and coverage reports
artifactsThe output to keep
cacheFiles to reuse between builds

A build fails as soon as any command returns a non-zero exit code, so a test runner that always exits with zero lets failing tests pass unnoticed.

version: 0.2
env:
  parameter-store:
    API_URL: /orders/prod/api-url
  secrets-manager:
    SONAR_TOKEN: ci/sonar:token
phases:
  install:
    runtime-versions:
      python: 3.13
    commands:
      - pip install -r requirements.txt -r requirements-dev.txt
  build:
    commands:
      - pytest --junitxml=reports/junit.xml
      - sam build
      - sam package --s3-bucket "$ARTIFACT_BUCKET" --output-template-file packaged.yaml
reports:
  unit-tests:
    files: [junit.xml]
    base-directory: reports
artifacts:
  files: [packaged.yaml]
cache:
  paths:
    - /root/.cache/pip/**/*
Put in order

Buildspec phases

Exam skills 3.3.5 · 3.1.2

Put the buildspec phases in the order CodeBuild runs them.

Log in to try this activity Interactive activities are free with an account.

Build environment

Each CodeBuild project defines the environment its builds run in, and most build failures that are not caused by the code itself come from these settings. The image provides the operating system and tools. AWS-managed images include common language runtimes, selected in the buildspec with runtime-versions, and a custom image stored in Amazon ECR can add any other tools a team needs. The compute type sets the memory and CPU available, and therefore the price per build minute.

Building container images requires access to the Docker daemon, which CodeBuild grants only when privileged mode is turned on for the project; without it, docker build fails with an error that it cannot connect to the daemon. Privileged mode should be enabled only for projects that need it, because it gives the build more control over its container.

By default, a build runs outside any VPC and can reach the internet and public AWS endpoints. When a build must reach private resources, such as a database for integration tests, the project is configured with a VPC, subnets and a security group. The build then has only private network access, so it needs a NAT gateway or VPC endpoints to download dependencies or call AWS APIs; placing it in a public subnet does not help, because the build receives no public IP address.

Everything a build does with AWS is authorised by the project's service role, an IAM role that CodeBuild assumes. A build that cannot push to ECR, read a parameter or upload an artifact is usually missing a permission in this role. Secrets are referenced in the env section from Parameter Store or Secrets Manager, as shown above, so they never appear in the buildspec or the project settings, and CodeBuild masks their values in the logs.

Scenario questions

Fix the failing build

Exam skills 4.1.4 · 3.3.5

Practise diagnosing CodeBuild failures from their symptoms.

Log in to try this activity Interactive activities are free with an account.

Logs, caching and reports

Every build writes its console output to Amazon CloudWatch Logs, to Amazon S3, or to both, which is the first place to look when a build fails. The log shows each phase and command, and the phase in which the failure occurred narrows the cause: a failure in install usually means a missing runtime or dependency, while one in build usually means a compilation or test failure.

Caching makes repeated builds faster by keeping files, such as downloaded dependencies, between builds. An S3 cache stores the paths listed in the buildspec's cache section in a bucket and works on any build host. A local cache keeps files on the build host itself and is faster, but it helps only when the next build happens to run on the same host; local Docker layer caching also requires privileged mode.

Test results published through the reports section are stored in report groups, which show pass rates, failures and code coverage over time, so a team can see whether quality is improving. The files listed in the artifacts section are uploaded to S3 or, when the build runs inside AWS CodePipeline, passed to the next stage as an output artifact.

Worked example

A build that passes when it should fail

A pipeline deploys code with failing tests. The buildspec runs pytest | tee results.txt. The pipe returns the exit code of tee, which succeeds, so CodeBuild never sees the test failure.

FixWhy
Run pytest --junitxml=reports/junit.xml without a pipepytest's non-zero exit code fails the build phase
Add a reports section for the JUnit fileTest results appear in CodeBuild reports
Use set -o pipefail if a pipe is neededThe pipeline fails if any command in it fails

CodeBuild decides success or failure only from exit codes; any tool in a build must signal failure that way.

Check yourself

How can CodeBuild avoid downloading the same dependencies in every build?

Show answer

By caching them: list the dependency folders under cache paths in the buildspec and enable an S3 or local cache on the project.

Exam Tips

Remember for the exam

  • If a build cannot find its instructions, the file must be buildspec.yml at the source root, or the location overridden.
  • If a build needs a password, reference Parameter Store or Secrets Manager in the env section.
  • If docker build fails in CodeBuild, enable privileged mode.
  • If a build passes even though tests fail, the test command is not returning a non-zero exit code.