Lesson 1 of 4 AWS CodeBuild

Understanding Build Projects in AWS CodeBuild

AWS CodeBuild is a fully managed continuous integration service that compiles source code, runs tests and produces deployable artifacts without any build servers to manage. This lesson introduces the building blocks of CodeBuild, explains what happens during a build and describes how builds are started, logged, priced and controlled.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the components of a CodeBuild project: source, environment, service role, buildspec, artifacts and logs.
  • Explain the sequence of phases that CodeBuild runs during a build and how phase failures are handled.
  • Identify the ways a build can be started and the environment variables CodeBuild provides.
  • Explain how CodeBuild is priced and which quotas and timeouts affect build design.

What CodeBuild Provides

Before managed build services, teams ran build servers such as Jenkins on their own instances. They had to patch the servers, scale them for peak demand, keep build tools installed and secure the credentials stored on them. CodeBuild removes this work. For each build, it provisions a fresh, isolated build environment, runs the commands that the build specification defines, uploads the outputs and then discards the environment. Builds do not share state unless caching is configured, so one build cannot be affected by files left behind by another.

CodeBuild scales automatically: many builds can run concurrently, up to an account quota, without any capacity planning. It integrates with AWS CodePipeline as a build or test action, but it can also run alone, started by a webhook, the console, the API or an EventBridge rule.

Components of a Build Project

A build project is the configuration that tells CodeBuild how to run a build. Each build is an execution of a project. A project has the following components.

Source
Where the code comes from: a Git provider through CodeConnections or OAuth, Amazon S3, AWS CodePipeline (the input artifact) or no source. A project can also have secondary sources, for example a second repository with shared scripts.
Environment
The compute and the container image the build runs in: operating system, architecture, compute size and either an AWS-managed image or a custom image from Amazon ECR or another registry.
Service role
The IAM role that CodeBuild assumes during the build. Every AWS API call made by the build, such as writing to S3 or pushing to ECR, uses this role's permissions.
Buildspec
A YAML file, normally buildspec.yml in the root of the source, that lists the commands to run in each phase and defines artifacts, reports, caching and environment variables. It can also be stored inline in the project or at another path.
Artifacts
The output files that CodeBuild uploads, usually to S3, or passes to CodePipeline as an output artifact.
Logs
Build output written to Amazon CloudWatch Logs, Amazon S3 or both.

Separating the buildspec from the project configuration is important. The project defines the infrastructure the build runs on and is usually managed by a platform team in a CloudFormation template; the buildspec defines what the build does and is owned by the application team in the repository, so it changes with the code.

The Life of a Build

Every build passes through a fixed sequence of phases. Some phases are performed by CodeBuild itself; others run the commands from the buildspec. Understanding the sequence is essential for troubleshooting, because the phase in which a build fails shows where to look.

  1. SUBMITTED and QUEUED: the build request is accepted and waits for capacity. A build waits in the queue if the concurrent build limit is reached.
  2. PROVISIONING: CodeBuild starts the build environment and pulls the container image.
  3. DOWNLOAD_SOURCE: the source code is downloaded and the buildspec is located and parsed. A missing or invalid buildspec fails here.
  4. INSTALL, PRE_BUILD, BUILD and POST_BUILD: the commands from the corresponding buildspec phases run.
  5. UPLOAD_ARTIFACTS: artifacts are uploaded and test reports are published.
  6. FINALIZING and COMPLETED: the environment is cleaned up and the build result is recorded.

Within a phase, commands run in order in the same shell instance (with buildspec version 0.2), so a variable set or a directory changed by one command is visible to the next. If any command returns a non-zero exit code, the phase fails. By default, a failure in INSTALL, PRE_BUILD or BUILD skips the remaining command phases except that POST_BUILD still runs after a BUILD failure, and the build is marked FAILED. This behaviour lets the POST_BUILD phase report results or clean up even when the build itself has failed; a finally block in a phase can also run commands regardless of success.

The following diagram shows the phases in order and what a failure does.

The phases of a CodeBuild build. SUBMITTED and QUEUED wait for capacity, PROVISIONING starts the environment and DOWNLOAD_SOURCE fetches the source and parses the buildspec, so an invalid buildspec fails there. INSTALL, PRE_BUILD, BUILD and POST_BUILD run the buildspec's commands; a non-zero exit code fails the phase. A failure in INSTALL, PRE_BUILD or BUILD skips the remaining command phases, except that POST_BUILD still runs after a BUILD failure. UPLOAD_ARTIFACTS, FINALIZING and COMPLETED follow.
The phase in which a build fails shows where to look.

Exit codes decide the result

Because a non-zero exit code fails the phase, any test framework that exits with a non-zero code when tests fail automatically fails the build. This is how CodeBuild, and therefore CodePipeline, measures the health of a build from exit codes. The Automated Testing module explains this in detail.

Put in order

Phases of a build

Exam skills 1.1.3

Put the phases of a CodeBuild build in order.

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

Starting Builds

A build can be started in several ways, and the method affects which source version is built:

  • As a CodePipeline action: the input artifact from a previous stage is the source, so the build uses exactly the revision that the pipeline captured.
  • By a webhook: a push or pull request in the Git provider starts the build for the commit that triggered the event.
  • By the API or CLI: StartBuild can override the source version, the buildspec, environment variables, the compute type and other settings for one build.
  • By EventBridge: a rule can start a build on a schedule or in response to any event.
  • Batch builds: StartBuildBatch runs several related builds, described in a later lesson of this module.

CodeBuild provides environment variables that describe the build, which buildspec commands commonly use. The most important are summarised below.

VariableMeaningCommon use
CODEBUILD_RESOLVED_SOURCE_VERSIONThe commit ID (or S3 object version) actually builtTagging images and artifacts with the commit
CODEBUILD_SOURCE_VERSIONThe requested source version, such as a branch, pull request reference or commitDetecting pull request builds
CODEBUILD_BUILD_ID and CODEBUILD_BUILD_NUMBERThe build's identifier and the project's incrementing build numberVersion strings and traceability
CODEBUILD_WEBHOOK_TRIGGERThe branch, tag or pull request that triggered a webhook buildDifferent behaviour for tags and branches
CODEBUILD_SRC_DIRThe directory where the primary source was downloadedPaths in scripts
AWS_REGION and AWS_DEFAULT_REGIONThe Region the build runs inAWS CLI and SDK calls

Logs, Monitoring and Debugging

Build output is streamed to a CloudWatch Logs log group, by default named /aws/codebuild/<project-name>, and can also be written to S3 for long-term retention. CodeBuild publishes CloudWatch metrics such as Builds, SucceededBuilds, FailedBuilds and Duration per project, and it emits build state change and phase change events to Amazon EventBridge. An EventBridge rule that matches FAILED build state events and sends them to an Amazon SNS topic is the standard way to notify a team of failed builds; notification rules in the developer tools console provide the same result with less configuration.

For difficult failures, a build can be paused for interactive debugging with AWS Systems Manager Session Manager. When session connection is enabled for the build and the buildspec runs the codebuild-breakpoint command, the build pauses and an engineer can open a shell in the build container, inspect files and then resume the build. Builds can also be run locally with the CodeBuild local agent to reproduce problems without consuming build minutes.

Scenario questions

Operate CodeBuild

Exam skills 1.1.3 · 5.3.1

Practise monitoring and debugging CodeBuild builds.

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

Pricing, Quotas and Timeouts

On-demand CodeBuild is charged per minute of build time, at a rate that depends on the compute type and operating system, from the moment the build starts provisioning until it completes. Queued time is not charged. Reserved capacity fleets, described in a later lesson, are charged for the time the fleet instances run instead. The following figures are defaults that shape build design.

60minutes

Default build timeout

36hours

Maximum build timeout (the minimum is 5 minutes)

8hours

Default and maximum queued timeout before a waiting build is stopped

The number of concurrent builds is limited per account and Region and per compute type; builds above the limit wait in the queue. A sudden increase in queued time in a busy organisation usually means that the concurrency quota has been reached, and the remedy is a quota increase or a reserved capacity fleet.

Worked example

Diagnosing a Build from Its Phases

A build fails and the console shows that DOWNLOAD_SOURCE succeeded, INSTALL succeeded, PRE_BUILD failed, BUILD was skipped and POST_BUILD ran. The PRE_BUILD phase runs aws ecr get-login-password | docker login ... and the log shows an AccessDeniedException.

The phase sequence shows that the source and buildspec were valid, so the problem is in the commands of PRE_BUILD. The error is an IAM authorisation failure on an AWS API call made by the build, and build commands use the project's service role. The fix is to add ecr:GetAuthorizationToken to the service role (the action applies to all resources) and repository-level permissions such as ecr:BatchCheckLayerAvailability, ecr:InitiateLayerUpload, ecr:UploadLayerPart, ecr:CompleteLayerUpload and ecr:PutImage on the target repository.

Check yourself

A build fails in the DOWNLOAD_SOURCE phase with a message that the YAML file cannot be parsed. Where is the problem?

Show answer

In the buildspec file. CodeBuild locates and parses the buildspec during DOWNLOAD_SOURCE, before any commands run, so an indentation or syntax error in buildspec.yml fails the build in this phase.

Exam Tips

Remember for the exam

  • Every AWS call a build makes uses the CodeBuild service role; AccessDenied errors in build commands are fixed by changing that role, not the pipeline role.
  • A non-zero exit code from any command fails the phase and the build; POST_BUILD still runs after a BUILD failure.
  • Use EventBridge rules on CodeBuild build state change events (or notification rules) with Amazon SNS to alert on failed builds.
  • Builds waiting in the QUEUED state indicate the concurrent build quota has been reached.
  • Session Manager with codebuild-breakpoint allows interactive debugging inside a running build.