Writing Buildspec Files
The buildspec file defines everything a CodeBuild build does: the commands in each phase, the environment variables, the artifacts it produces, the reports it publishes and the files it caches. This lesson works through every section of the buildspec, explains how each one behaves and shows complete examples for common build types.
Learning outcomes
After completing this lesson, you will be able to:
- Describe the purpose and behaviour of each section of a buildspec file.
- Explain how primary and secondary artifacts are defined and how file paths are resolved.
- Explain how exported variables pass values from a build to later pipeline actions.
- Interpret a buildspec for a container image build and identify the permissions and settings it requires.
Structure of a Buildspec
A buildspec is a YAML document whose top-level keys define the build. The version key is required and should be 0.2; version 0.1 runs each command in a separate shell and is deprecated. The other top-level sections are optional, and each is described below.
version: 0.2
run-as: root # optional Linux user for all commands
env:
shell: bash
variables:
APP_ENV: "test"
parameter-store:
DB_USER: "/orders/test/db-user"
secrets-manager:
DB_PASSWORD: "orders/test/db:password"
exported-variables:
- IMAGE_TAG
phases:
install:
runtime-versions:
python: 3.12
commands:
- pip install -r requirements.txt
pre_build:
commands:
- pytest --junitxml=reports/unit.xml --cov=app --cov-report=xml:reports/coverage.xml
build:
on-failure: ABORT
commands:
- export IMAGE_TAG=${CODEBUILD_RESOLVED_SOURCE_VERSION:0:8}
- python -m build
post_build:
commands:
- echo "Build finished with status $CODEBUILD_BUILD_SUCCEEDING"
reports:
unit-tests:
files: ["unit.xml"]
base-directory: reports
file-format: JUNITXML
coverage:
files: ["coverage.xml"]
base-directory: reports
file-format: COBERTURAXML
artifacts:
files:
- "dist/**/*"
- appspec.yml
discard-paths: no
cache:
paths:
- "/root/.cache/pip/**/*"The env Section
The env section defines environment variables available to every command. Values can come from four places, and choosing the right one is a common exam requirement.
variables
Plain-text key-value pairs. They are visible in the buildspec, in the project configuration if set there, and in build details. They are appropriate for non-sensitive settings such as an environment name or a feature toggle.
parameter-store
Maps an environment variable to an AWS Systems Manager Parameter Store parameter name. CodeBuild retrieves the value at the start of the build using the service role, which needs ssm:GetParameters on the parameter and, for a SecureString encrypted with a customer managed key, kms:Decrypt on that key.
secrets-manager
Maps an environment variable to an AWS Secrets Manager secret. The reference format is secret-id:json-key:version-stage:version-id, where every part after the secret ID is optional. For a secret that stores a JSON object such as {"username":"app","password":"..."}, the reference orders/test/db:password extracts only the password. The service role needs secretsmanager:GetSecretValue on the secret.
exported-variables
Lists environment variables whose final values at the end of the build are exported. When the build runs as a CodePipeline action with a namespace, later actions can reference them, for example #{BuildVariables.IMAGE_TAG}. This is how a build passes a computed image tag or version number to a deployment action without writing a file.
CodeBuild masks values that come from Parameter Store and Secrets Manager in build logs. Other settings in env include shell (the shell to use), git-credential-helper (lets Git commands use the build's credentials) and variables overrides supplied when a build is started.
Where should the value come from?
The phases Section
The four phases have conventional purposes. CodeBuild does not enforce what each phase does, but following the conventions makes buildspecs easier to read and makes failure handling predictable.
- install: installs tools and runtimes. The
runtime-versionskey selects language runtimes provided by the managed image, such asnodejs: 22orjava: corretto21. - pre_build: prepares the build, for example by signing in to Amazon ECR, downloading dependencies or running fast tests and linting.
- build: compiles, packages or builds container images.
- post_build: publishes outputs, such as pushing an image, writing an image definitions file or sending a notification. It runs even when the build phase fails, so commands that must not run after a failure should check
CODEBUILD_BUILD_SUCCEEDING, which is1when the build is succeeding and0after a failure.
Each phase can contain commands, a finally block that always runs after the commands, run-as to change the user, and on-failure. Setting on-failure: ABORT stops the build immediately when the phase fails, including skipping POST_BUILD; on-failure: CONTINUE continues with the next phase despite the failure. The build result is still FAILED if any phase failed.
Buildspec behaviour
The artifacts Section
The artifacts section lists the files CodeBuild uploads after the build. Paths are relative to the original build location or to base-directory if set, and glob patterns such as **/* are supported. discard-paths: yes flattens the directory structure, and name sets the artifact name, which can include environment variables to create versioned names.
A build can produce several outputs with secondary-artifacts, each identified by an artifact identifier. In CodePipeline, each identifier maps to one of the action's output artifacts, which lets a single build produce, for example, an application package for CodeDeploy and a CloudFormation template bundle for a deploy action. When a pipeline action has several input artifacts, the primary one is downloaded to CODEBUILD_SRC_DIR and the others to directories referenced by CODEBUILD_SRC_DIR_<ArtifactName>.
Artifacts not found
When a pipeline build produces no output, the cause is often an artifacts pattern that does not match the build output location. CodeBuild reports an error such as "no matching artifact paths found" in the UPLOAD_ARTIFACTS phase. Check the path relative to the base directory.
The reports and cache Sections
The reports section publishes test and code coverage results to CodeBuild report groups, where they can be viewed as trends over time. Each report specifies the files, an optional base directory and a file format. Supported test formats include JUnit XML, Cucumber JSON, TestNG XML, Visual Studio TRX and NUnit XML; supported coverage formats include JaCoCo XML, Cobertura XML, Clover XML and SimpleCov JSON. Report groups are covered in depth in the Automated Testing module.
The cache section lists paths, such as a dependency directory, that CodeBuild saves after a build and restores before the next one. Whether the cache is stored in S3 or locally on the build host is a project setting, explained in the next lesson.
Building and Pushing a Container Image
The following buildspec builds a Docker image, tags it with the short commit ID, pushes it to Amazon ECR and writes an imagedefinitions.json file, which the CodePipeline Amazon ECS standard deploy action uses to update a service.
version: 0.2
env:
variables:
REPO_NAME: "orders"
CONTAINER_NAME: "orders-web"
exported-variables:
- IMAGE_URI
phases:
pre_build:
commands:
- ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
- REGISTRY=$ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com
- aws ecr get-login-password | docker login --username AWS --password-stdin $REGISTRY
- IMAGE_TAG=${CODEBUILD_RESOLVED_SOURCE_VERSION:0:8}
- IMAGE_URI=$REGISTRY/$REPO_NAME:$IMAGE_TAG
build:
commands:
- docker build -t $IMAGE_URI .
post_build:
commands:
- |
if [ "$CODEBUILD_BUILD_SUCCEEDING" = "1" ]; then
docker push $IMAGE_URI
printf '[{"name":"%s","imageUri":"%s"}]' "$CONTAINER_NAME" "$IMAGE_URI" > imagedefinitions.json
fi
artifacts:
files:
- imagedefinitions.jsonThree project settings are required for this buildspec to work. First, the environment must have privileged mode enabled, because building Docker images requires the Docker daemon inside the build container. Second, the service role needs the ECR permissions listed in the previous lesson. Third, the build must reach the ECR endpoints, either through the internet when the build is not in a VPC, or through a NAT gateway or ECR interface VPC endpoints when it is. The post_build check prevents pushing an image when the build phase failed.
A build action must pass the version number it computes to a later CloudFormation deploy action as a parameter. How should the version be passed?
Show answer
List the variable under env exported-variables in the buildspec, give the CodeBuild action a variable namespace in the pipeline, and reference it in the deploy action configuration as #{Namespace.VARIABLE}.
Exam Tips
Remember for the exam
- Use buildspec version 0.2; commands in a phase share one shell, so variables persist between commands.
- Reference secrets with env parameter-store or env secrets-manager; the service role needs ssm:GetParameters or secretsmanager:GetSecretValue, plus kms:Decrypt for customer managed keys.
- exported-variables plus a pipeline action namespace pass build values to later actions as #{Namespace.Var}.
- Docker image builds need privileged mode on the CodeBuild environment.
- post_build runs after a build failure unless on-failure: ABORT is set; guard publishing commands with CODEBUILD_BUILD_SUCCEEDING.
- secondary-artifacts let one build produce several pipeline output artifacts.