Back to Blog

AWS CodeBuild Internals for the DOP-C02 Exam: Every buildspec Section, the Phase Transition Rules (Why post_build Runs After a Failed build), on-failure RETRY & finally Blocks, Environment Variable Precedence & Secret Masking, Batch Builds (build-graph, build-list, build-matrix, build-fanout), S3 Cache Keys vs the Three Local Cache Modes, On-Demand vs Reserved Capacity Fleets vs Lambda Compute, Webhook Filter Groups & Pull Request Build Policies, Timeouts, Concurrency, Auto-Retry and Debugging with codebuild-breakpoint

A practitioner's deep dive into AWS CodeBuild for the AWS DevOps Engineer Professional (DOP-C02) exam — the full buildspec reference (run-as, env/parameter-store/secrets-manager/exported-variables, phases with on-failure ABORT/CONTINUE/RETRY and finally blocks, reports, artifacts, cache), the phase transition diagram and why POST_BUILD and UPLOAD_ARTIFACTS still run after a failed BUILD, environment variable precedence (start-build > project > buildspec), batch builds with build-graph/build-list/build-matrix/build-fanout and the separate batch service role, S3 caching with codebuild-hash-files keys and fallback keys vs LOCAL_SOURCE_CACHE / LOCAL_DOCKER_LAYER_CACHE / LOCAL_CUSTOM_CACHE, on-demand fleets vs reserved capacity fleets (overflow behavior, attribute-based compute, custom AMIs) vs Lambda compute and its limitations, webhook filter groups (EVENT, HEAD_REF, BASE_REF, FILE_PATH, ACTOR_ACCOUNT_ID, COMMIT_MESSAGE) and pull request comment approval, build and queued timeouts, concurrent build limits, auto-retry, VPC builds, and debugging with codebuild-breakpoint and the sandbox.

By Sailor Team , November 22, 2026

CodeBuild is the service every DOP-C02 candidate has used and almost nobody has read the reference for. You know a buildspec.yml has phases, you know post_build pushes the image, and you know builds can be cached. Then the exam asks why a Docker push in post_build ran even though the unit tests in build failed, why a secret you retrieved from Secrets Manager appeared in the logs after you Base64-encoded it, why a batch build that bypassed its compute restrictions needs a second IAM role, why a reserved capacity fleet with overflow set to on-demand produced a surprise bill, or why a FILE_PATH webhook filter stopped working on a large pull request, and the answer is a mechanism inside CodeBuild, not a feature name.

This guide covers those mechanisms. Our SDLC Automation guide places CodeBuild in the pipeline and shows a minimal buildspec, the CodePipeline V2 internals post covers what triggers the build and how the Commands action competes with it, the CodeArtifact post and the Amazon ECR internals post cover where the build’s dependencies come from and where its images go, and the EC2 Image Builder post covers the AMI pipeline that often sits next to it. This post assumes those and goes inside the build itself: the buildspec section by section, the phase transition rules, environment variables and secrets, batch builds, caching, the three compute models, webhooks and pull request policies, timeouts and concurrency, and how to debug a build that only fails in CodeBuild.

Everything below is verified against the CodeBuild User Guide as of November 2026.

Where CodeBuild Sits in the DOP-C02 Blueprint

CodeBuild lives in Domain 1 (SDLC Automation, 22%), the largest domain on the exam. Task 1.1 (implement CI/CD pipelines) expects you to configure the build stage and its triggers, Task 1.2 (integrate automated testing) expects you to know where unit, integration and security tests run and how their results surface, and Task 1.3 (build and manage artifacts) expects you to know how CodeBuild produces, names, encrypts and caches artifacts. CodeBuild also leaks into Domain 2 (building AMIs and container images at scale), Domain 4 (build metrics, logs and EventBridge events) and Domain 6 (secrets in builds, least-privilege service roles, VPC-only builds).

The exam rarely names a buildspec key outright. It describes a symptom, a cost or a security requirement and lets four plausible CodeBuild settings compete. The rest of this guide gives you the mechanisms behind each setting so the right one is recognisable.

The buildspec, Section by Section

A buildspec is a YAML collection of build commands and settings. By default it is buildspec.yml in the root of the source. Three things about its location matter on the exam:

  • A project has exactly one buildspec, but you can point to a different file name or path: the project’s buildspec setting (a path relative to CODEBUILD_SRC_DIR, such as config/buildspec_release.yml), the buildspecOverride parameter of start-build, or the BuildSpec property under Source in CloudFormation. This is how one repository runs buildspec_debug.yml in one project and buildspec_release.yml in another.
  • The buildspec can live in S3 instead of the repository, referenced by ARN (arn:aws:s3:::bucket/buildspec.yml), and the bucket must be in the same Region as the project. An inline buildspec (defined in the project itself) or an S3 buildspec is visible only to the project owner, which is the documented defence against a pull request that modifies buildspec.yml to run unwanted commands on a public repository.
  • Version 0.2 vs 0.1. In version 0.1 every command ran in a separate shell instance, so cd or export in one command did not affect the next. Version 0.2 runs all commands in the same shell instance. Version 0.2 also renamed environment_variables to env, plaintext to variables, and deprecated the artifacts type property. Always use 0.2.

The full syntax, trimmed to the keys the exam cares about:

version: 0.2
run-as: Linux-user-name              # optional, Linux only, default root
env:
  shell: bash                        # bash | /bin/sh | powershell.exe | cmd.exe
  variables:
    KEY: "value"
  parameter-store:
    KEY: "/path/in/parameter/store"
  secrets-manager:
    KEY: secret-id:json-key:version-stage:version-id
  exported-variables:
    - KEY
  git-credential-helper: yes
proxy:
  upload-artifacts: yes
  logs: yes
batch:
  fast-fail: false
  # build-list: | build-matrix: | build-graph: | build-fanout:
phases:
  install:
    run-as: Linux-user-name
    on-failure: ABORT | CONTINUE | RETRY | RETRY-count | RETRY-regex | RETRY-count-regex
    runtime-versions:
      nodejs: 20
    commands:
      - command
    finally:
      - command
  pre_build:   { commands: [...], finally: [...] }
  build:       { commands: [...], finally: [...] }
  post_build:  { commands: [...], finally: [...] }
reports:
  report-group-name-or-arn:
    files: [ location ]
    base-directory: location
    discard-paths: no
    file-format: JUNITXML
artifacts:
  files: [ location ]
  name: artifact-name
  discard-paths: no
  base-directory: location
  exclude-paths: pattern
  enable-symlinks: no
  s3-prefix: prefix
  secondary-artifacts:
    artifactIdentifier: { files: [...], name: ... }
cache:
  key: key
  fallback-keys: [ fallback-key ]
  action: restore | save
  paths: [ path ]

run-as

Commands run as root unless run-as names another Linux user. A top-level run-as applies to every phase; a phase-level run-as overrides it for that phase only. It is Linux-only. Exam cue: “the build must not run as root” is run-as, not a custom image.

env: variables, parameter-store, secrets-manager

env/variables holds plain-text variables. Two rules trip people up. First, any variable you set replaces the image’s variable of the same name, including PATH: setting PATH to $PATH:/usr/share/ant/bin replaces the image’s PATH with that literal string. Second, names starting with CODEBUILD_ are reserved.

env/parameter-store maps a local name to a Systems Manager Parameter Store parameter name; the service role needs ssm:GetParameters. env/secrets-manager uses a colon-separated reference:

env:
  secrets-manager:
    DB_PASSWORD: "prod/db:password"                 # secret name : json-key
    API_KEY: "arn:aws:secretsmanager:us-east-1:111122223333:secret:x:apikey::"

The pattern is <secret-id>:<json-key>:<version-stage>:<version-id>. The secret ID is a name for a same-account secret or an ARN for a cross-account secret; omit the JSON key to receive the whole secret string; version stage and version ID are mutually exclusive and default to AWSCURRENT.

Masking. CodeBuild hides AWS access key IDs and any value retrieved through parameter-store or secrets-manager from the build logs, but masking matches the exact stored value. If a command Base64-encodes, reverses, upper-cases or concatenates the secret before printing it, the result is a different string and it appears in the logs. The documented fix is to store the secret in the form the build uses, for example store the Base64-encoded value directly. Plain env/variables are never masked and are visible in the console and CLI, which is why the exam’s answer for “database password in the build” is always Parameter Store (SecureString) or Secrets Manager, never a plain variable.

Environment variable precedence

When the same name is defined in several places:

  1. the start build call (environmentVariablesOverride, or the console’s “Start build with overrides”) wins,
  2. then the project definition,
  3. then the buildspec declaration, which has the lowest precedence.

So a buildspec cannot override a project variable, and a pipeline that starts the build with an override beats both. Remember this when a scenario asks why a STAGE=prod override “did not apply” (it was set in the buildspec, below the project value).

exported-variables

env/exported-variables lists variables to publish to CodePipeline as output variables of the build action, so later stages can reference them through the action’s namespace. The value is available from the install phase onward, can change until the end of post_build, and is frozen after post_build ends. You cannot export Parameter Store or Secrets Manager secrets declared in the project, nor any variable starting with AWS_.

git-credential-helper and proxy

git-credential-helper: yes lets CodeBuild supply Git credentials for private submodules or dependencies fetched by git; it is not supported for builds triggered by a webhook on a public repository. The proxy block only matters when the build runs behind an explicit proxy server: upload-artifacts and logs default to no, so a proxied build produces no artifacts and no CloudWatch logs until you set them to yes.

Phases: Order, Failure, on-failure and finally

The four user phases always run in the order install → pre_build → build → post_build. If any command in a phase fails, the phase fails. What happens next is the single most tested CodeBuild fact, and it is governed by the phase transition diagram in the User Guide.

The phase transition rules

The full build moves through these phases:

SUBMITTED → QUEUED → PROVISIONING → DOWNLOAD_SOURCE → INSTALL → PRE_BUILD
          → BUILD → POST_BUILD → UPLOAD_ARTIFACTS → FINALIZING → COMPLETED

The diagram shows three different failure paths:

Phase that failsWhat runs next
PROVISIONING, DOWNLOAD_SOURCE, INSTALL, PRE_BUILDJump straight to FINALIZING → COMPLETED. BUILD, POST_BUILD and UPLOAD_ARTIFACTS are skipped.
BUILDPOST_BUILD still runs, then UPLOAD_ARTIFACTS, then FINALIZING.
POST_BUILDUPLOAD_ARTIFACTS still runs, then FINALIZING.

The User Guide states it bluntly: the UPLOAD_ARTIFACTS phase is always attempted, even if the BUILD phase fails. The practical consequence is the classic exam scenario: tests fail in build, but the docker push in post_build runs anyway and a broken image reaches ECR. The fix is the built-in variable CODEBUILD_BUILD_SUCCEEDING, which is 1 while the build is succeeding and 0 once it is failing:

post_build:
  commands:
    - |
      if [ "$CODEBUILD_BUILD_SUCCEEDING" = "1" ]; then
        docker push $REPO:$CODEBUILD_RESOLVED_SOURCE_VERSION
      else
        echo "Build failed, skipping push"
      fi

Another consequence: CODEBUILD_RESOLVED_SOURCE_VERSION is only available after DOWNLOAD_SOURCE, so it is empty in a PROVISIONING failure message and in builds whose source is an unversioned S3 object.

on-failure

Each phase accepts an on-failure action that overrides the default transition for that phase:

ValueBehaviour
ABORTAbort the build (the default transition behaviour).
CONTINUEContinue to the next phase even though this phase failed.
RETRYRetry the build up to 3 times for any error (regex .*).
RETRY-countRetry up to count times (0 to 100), for example RETRY-8.
RETRY-regexRetry up to 3 times only when the error message matches regex, for example RETRY-.*connection timed out.*.
RETRY-count-regexBoth: RETRY-3-.*connection timed out.*.

Two restrictions matter: on-failure is not supported on Lambda compute or on reserved capacity fleets; it works only with EC2 on-demand compute images provided by CodeBuild. And RETRY retries the build, not the command, which is different from the project-level auto-retry described later.

finally

A finally block runs after the phase’s commands, even if a command failed: if the first of three commands fails, the remaining two are skipped and finally runs. The phase succeeds only when every command in both commands and finally succeeds. Use it for cleanup, log uploads and docker logout, not for work that depends on the phase having succeeded.

install and runtime-versions

runtime-versions under install selects runtimes on the curated Ubuntu standard 5.0+ and Amazon Linux 2 standard 4.0+ images. You can pin an exact version (ruby: 3.2), a major with .x (nodejs: 18.x), latest, or an environment variable. If you specify none, CodeBuild picks the image’s defaults, which change when a default reaches end of life, so the documented best practice is to pin. Two conflicting runtimes (android: 29 with java: openjdk11) fail the build, and a runtime-versions section on an image that does not support it produces the warning “Skipping install of runtimes”.

reports: Test and Coverage Reports

The reports block publishes raw test files into report groups. A project can send to at most five report groups. Name an existing group by ARN, or give a new name and CodeBuild creates <project-name>-<report-group-name> on the first build. Each group takes files (globs such as '**/*'), an optional base-directory, discard-paths (flatten directories) and a file-format:

KindFormats
Test reportsCUCUMBERJSON, JUNITXML (default), NUNITXML, NUNIT3XML, TESTNGXML, VISUALSTUDIOTRX
Code coverage reportsCLOVERXML, COBERTURAXML, JACOCOXML, SIMPLECOV

Report facts the exam reuses: a report expires 30 days after creation, and the only way to keep results longer is to configure the report group to export raw files to an S3 bucket (exported files never expire). A report holds at most 500 test cases. Report auto-discovery is on by default: after the build phase CodeBuild scans **/* for supported report files and creates groups named <project-name>-<file-format>-AutoDiscovered; disable it with the project variable CODEBUILD_CONFIG_AUTO_DISCOVER=false or narrow it with CODEBUILD_CONFIG_AUTO_DISCOVER_DIR. Reports are how Task 1.2’s “surface test results and trends in the pipeline” is implemented without any third-party tool.

artifacts: Naming, Packaging and Secondary Artifacts

artifacts/files is always required when an artifacts block exists, even if only secondary artifacts are defined. Paths are relative to the build location (CODEBUILD_SRC_DIR) or to base-directory; '**/*' means everything recursively. Matching top-level directories named in base-directory are not included themselves, only their contents.

  • discard-paths: yes flattens the directory structure in the output.
  • exclude-paths removes paths relative to base-directory; **/.*/**/* excludes dot folders.
  • enable-symlinks: yes preserves internal symlinks when the output type is ZIP.
  • s3-prefix applies when the namespace type is BUILD_ID: the object path becomes <s3-prefix>/<build-id>/<name>.zip.
  • packaging on the project is NONE (a folder, the default) or ZIP.
  • Uploaded objects carry the S3 metadata header x-amz-meta-codebuild-buildarn so you can trace an artifact back to its build.

Artifact names calculated at build time. artifacts/name can use shell command language, for example name: myname-$(date +%Y-%m-%d) or name: builds/$CODEBUILD_BUILD_NUMBER/my-artifacts (which also creates directories). The buildspec name only takes effect when the project sets overrideArtifactName: true (the console calls this Enable semantic versioning). Without that flag, the project’s artifact name wins and the buildspec name is ignored, a frequent “why is my artifact always overwritten” scenario.

Secondary artifacts. secondary-artifacts maps artifact identifiers to definitions with the same syntax as the primary block; each identifier must match an entry in the project’s secondaryArtifacts, and a project can declare up to 12. Secondary sources work the same way: CODEBUILD_SRC_DIR_<sourceIdentifier> and CODEBUILD_SOURCE_VERSION_<sourceIdentifier> locate each extra source.

Artifacts are encrypted with the default AWS managed key or the project’s encryptionKey; encryptionDisabled exists for the “host build output as a public website” scenario.

cache: Amazon S3 Caching vs Local Caching

CodeBuild offers two cache types and the exam expects you to pick by workload.

Amazon S3 caching

S3 caching stores the cache in a bucket available across build hosts, the right choice for small-to-medium dependency sets that are more expensive to build than to download. You list paths in the buildspec; if you list none, CodeBuild makes a best-effort cache of common language dependencies. The interesting behaviour arrives when you add a key:

cache:
  key: npm-$(codebuild-hash-files package-lock.json)
  fallback-keys:
    - npm-
  action: restore        # restore | save | (omitted = both)
  paths:
    - "node_modules/**/*"
  • key is matched exactly. codebuild-hash-files computes a SHA-256 over the files matching its glob patterns, so a changed lock file produces a new key and therefore a new, immutable cache copy. Keys can also embed variables such as $CODEBUILD_RESOLVED_SOURCE_VERSION.
  • fallback-keys lists up to five keys tried in order with a prefix search when the primary key misses; they are ignored unless key is set.
  • action: restore only restores, action: save only saves; omitted means both.
  • The cache version is a hash of the cached paths, so two caches with the same key but different paths are distinct.
  • Cross-project sharing uses the project’s cacheNamespace (--cache '{"type":"S3","location":"bucket","cacheNamespace":"x"}'): projects share a cache only when the namespace, key, paths, bucket and pathPrefix all match.

Local caching

Local caching keeps the cache on the build host, so it helps only when the next build lands on the same host; the User Guide says it is a good option for intermediate to large artifacts and a poor one for infrequent builds. You choose one or more of three modes:

ModeWhat it cachesRules
LOCAL_SOURCE_CACHEGit metadata for primary and secondary sources; later builds pull only the delta between commitsIgnored if the source is not a Git repository (S3 sources)
LOCAL_DOCKER_LAYER_CACHEExisting Docker layers, for projects that build or pull large imagesLinux only; privileged mode must be enabled; consider the security implications
LOCAL_CUSTOM_CACHEDirectories you list under cache/pathsDirectories only, not files; cached directories are symlinked in before the source is downloaded and a cached directory overrides a source directory of the same name

Local caching is not supported for VPC-connected builds, nor with the LINUX_GPU_CONTAINER environment type or the BUILD_GENERAL1_2XLARGE compute type. The CLI form is --cache type=LOCAL,mode=[LOCAL_DOCKER_LAYER_CACHE]; in CloudFormation the Cache.Type is LOCAL with Modes, and Docker layer caching requires PrivilegedMode: true and Type: LINUX_CONTAINER.

Exam decision rule: “builds run in a VPC” or “many different projects need the same dependency cache” → S3 cache; “large Docker images rebuilt many times a day” → Docker layer cache (plus privileged mode); “huge monorepo clone dominates build time” → source cache (or a small Git clone depth).

Batch Builds: build-graph, build-list, build-matrix, build-fanout

A batch build runs several coordinated builds from one project. The batch block selects one of four types, and every task shares the project’s env and phases unless a task overrides them with a different buildspec or env.

TypeSemanticsTypical use
build-graphTasks with depend-on lists; a task waits for its dependencies to completeBuild → integration test → package chains
build-listIndependent tasks that run in parallelDifferent targets or platforms with different buildspecs
build-matrixstatic settings applied to all, dynamic arrays of buildspec, image, compute-type, variables; CodeBuild creates one build per combination2 buildspecs × 3 variable values = 6 parallel builds
build-fanoutOne task split into parallelism shards; codebuild-tests-run splits the test files across the shardsParallel test execution

Per-task fields are identifier (required), buildspec, debug-session, depend-on (graph only), ignore-failure (a failed task does not fail the batch) and env with compute-type, fleet, image, privileged-mode, type and variables. compute-type and fleet cannot both be set on one task. batch/fast-fail: true stops every running build as soon as one task fails; the default false lets running builds complete. Inside each build, CODEBUILD_BATCH_BUILD_IDENTIFIER carries the task identifier.

Fan-out example from the User Guide:

version: 0.2
batch:
  fast-fail: false
  build-fanout:
    parallelism: 5
    ignore-failure: false
phases:
  build:
    commands:
      - |
        codebuild-tests-run \
          --test-command 'npx jest --runInBand --coverage' \
          --files-search "codebuild-glob-search '**/test/**/*.test.js'" \
          --sharding-strategy 'equal-distribution'

With 100 tests and parallelism: 5, CodeBuild starts five identical builds that each run 20 tests. If reports are configured, each fan-out build publishes its own report.

The batch service role. Batch builds require a second IAM role in the project’s batch configuration because CodeBuild must call StartBuild, StopBuild and RetryBuild on your behalf. The User Guide explains why it must not be the build role: granting those actions to the build role would let any build start more builds from its buildspec, and it would let builds bypass the batch restrictions (maximumBuildsAllowed, computeTypesAllowed, fleetsAllowed) that cap what a batch may consume. The batch configuration also sets timeoutInMinutes for the whole batch, combineArtifacts (merge every task’s artifacts into one location) and batchReportMode, which is REPORT_AGGREGATED_BATCH (one combined status to GitHub, GitHub Enterprise or Bitbucket, the default) or REPORT_INDIVIDUAL_BUILDS.

Compute: On-Demand Fleets, Reserved Capacity Fleets and Lambda

CodeBuild has two compute modes, EC2 and Lambda, and EC2 has two fleet types. Choosing among them is a Domain 1 and Domain 2 cost question.

On-demand EC2 compute types

On-demand fleets are fully managed; machines are created per build and destroyed when it finishes. The compute types that appear in exam answers:

Compute typecomputeTypeMemoryvCPUsDisk
Linux / ARM SmallBUILD_GENERAL1_SMALL4 GiB264 GB
Linux / ARM MediumBUILD_GENERAL1_MEDIUM8 GiB4128 GB
Linux / ARM LargeBUILD_GENERAL1_LARGE16 GiB8128 GB
Linux XLargeBUILD_GENERAL1_XLARGE72 GiB36256 GB
Linux 2XLargeBUILD_GENERAL1_2XLARGE144 GiB72824 GB SSD
Linux GPU Small / LargeBUILD_GENERAL1_SMALL / LARGE on LINUX_GPU_CONTAINER16 / 255 GiB4 / 32235 GB SSD / 50 GB

Environment types pair with them: LINUX_CONTAINER, ARM_CONTAINER, LINUX_GPU_CONTAINER, WINDOWS_SERVER_2019_CONTAINER, WINDOWS_SERVER_2022_CONTAINER, and the LINUX_EC2 / ARM_EC2 / WINDOWS_EC2 types that run directly on an instance instead of in a container. The disk space is available only under CODEBUILD_SRC_DIR; Amazon EFS can be mounted for more. Custom images may be up to 50 GB uncompressed (100 GB on 2XLarge). Image tip from the docs: the latest version of each curated image is cached on the hosts, so aws/codebuild/amazonlinux-x86_64-standard:5.0 provisions faster than the pinned 5.0-1.0.0.

Privileged mode is required to build Docker images (and for the Docker layer cache); it is unsupported on Windows. The Docker daemon is enabled by default for non-VPC builds; VPC builds that need Docker must enable privileged mode.

Lambda compute

BUILD_LAMBDA_1GB through BUILD_LAMBDA_10GB on ARM_LAMBDA_CONTAINER or LINUX_LAMBDA_CONTAINER give faster start-up and automatic scaling (no queueing), with 10 GB of disk. Curated Lambda images include the AWS CLI v2, SAM CLI, git, Go, Java, Node.js, Python, Ruby and .NET; custom images are allowed (single-architecture only, must contain curl or wget). The limitations list is the exam material:

  • no tools that need root (no yum, no rpm), no Docker builds or runs, no writes outside /tmp;
  • no caching, no custom build timeout, no queued timeout, no build badges, no privileged mode, no custom runtime environments, and a hard 15-minute runtime;
  • no VPC connectivity, no fixed source IP range, no EFS, no certificates, no Session Manager access;
  • no on-failure in the buildspec;
  • a cancelled GitHub Actions job keeps running on Lambda until the 15-minute limit and ends FAILED with TIMED_OUT, whereas EC2 compute stops it in seconds.

So “fast, short, no Docker, no VPC” → Lambda; anything that builds an image, runs longer than 15 minutes or reaches a private database → EC2.

Reserved capacity fleets

A reserved capacity fleet is a set of dedicated EC2 instances maintained by CodeBuild that stay running and idle between builds, which removes provisioning time. The billing is the trap: instances incur an initial charge per instance and keep incurring cost as long as they are provisioned, whether or not builds run. Fleet properties:

  • Capacity is the number of instances, which is the number of builds that can run in parallel. Optional scaling raises it on demand.
  • Overflow behavior when builds exceed capacity: ON_DEMAND runs the extra builds on CodeBuild on-demand (billed separately, and a VPC-connected fleet then needs the VPC permissions on the project service role) or QUEUE holds them until an instance frees up, which caps cost.
  • Compute selection: guided (vCPU, memory, disk), a custom EC2 instance type (instanceType), or attribute-based compute (ATTRIBUTE_BASED_COMPUTE with a computeConfiguration of vCPUs, memory, disk and machineType GENERAL or NVME), where CodeBuild picks the cheapest instance whose memory, vCPUs and disk all meet or exceed the request and fails validation if nothing matches. If the resolved configuration is not available on-demand, an on-demand overflow setting silently becomes queue behaviour.
  • Operating systems: Amazon Linux (x86_64 or Arm64, environment types Linux EC2 or Linux GPU), Windows Server 2019/2022, and macOS, which is reserved-capacity only (Apple M2 with 24 GB / 8 vCPUs or 32 GB / 12 vCPUs) and limited to a handful of Regions. On-demand fleets do not support macOS at all.
  • Custom AMIs must allow the CodeBuild service organization ARN for the Region, an encrypted AMI’s KMS key policy must allow the CodeBuild organization ID through aws:PrincipalOrgID, and the fleet service role needs ec2:DescribeImages and ec2:DescribeSnapshots.
  • VPC fleets support only one subnet in a single Availability Zone and need a NAT gateway; a fleet override on StartBuild makes CodeBuild ignore the project’s VPC configuration. Proxy configurations (allow or deny outbound by default plus domain or IP rules) apply to Amazon Linux fleets and do not combine with VPC, Windows or macOS.
  • Sharing: a fleet can serve many projects, and the docs warn that data cached on fleet instances (source files, Docker layers, cached directories) is accessible to other projects in the same account by design.
  • Limitations: no build utilization metrics, no debug session on macOS fleets, no buildspec on-failure, and a default quota of 10 fleets.

Exam decision rule: “builds wait minutes in PROVISIONING” or “macOS/iOS build” → reserved capacity; “cost must not exceed the fleet” → overflow QUEUE; “spiky, infrequent” → on-demand.

Webhooks, Filter Groups and Pull Request Build Policies

CodeBuild webhooks work with GitHub, GitHub Enterprise Server, GitLab, GitLab Self Managed, Bitbucket and (manual) Buildkite. A build is triggered when any filter group evaluates to true, and a group is true only when all of its filters are true. Each group names one or more events and optional filters, which are RE2 regular expressions (no lookahead, lookbehind, backreferences or atomic groups).

GitHub events: PUSH, PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_REOPENED (GitHub and GHES only), PULL_REQUEST_MERGED, PULL_REQUEST_CLOSED, RELEASED, PRERELEASED (GitHub only) and WORKFLOW_JOB_QUEUED. A pull_request payload whose action is closed maps to PULL_REQUEST_MERGED when merged is true and to PULL_REQUEST_CLOSED otherwise.

FilterMatchesRestrictions
ACTOR_ACCOUNT_IDThe sender’s account IDDocumented best practice for public repositories: allow only trusted users to trigger builds
HEAD_REFrefs/heads/branch or refs/tags/tag of the push or the PR head—
BASE_REFThe PR base branchPull request events only
FILE_PATHPath of a changed fileEvaluated against the first 100 changed files only; push and PR on GitHub, push only on GHES
COMMIT_MESSAGEHead commit messageSame provider limits as FILE_PATH
TAG_NAME, RELEASE_NAMERelease tag or nameReleased / prereleased events
REPOSITORY_NAME, ORGANIZATION_NAMEFor organization or global webhooksOrganization name is global webhooks only
WORKFLOW_NAMEGitHub Actions workflow nameWORKFLOW_JOB_QUEUED events

Each filter can be negated with excludeMatchedPattern, which is the console’s “Don’t start a build under these conditions”. The User Guide’s public-repository hardening checklist is worth memorising as a set: add ACTOR_ACCOUNT_ID filters, exclude ^buildspec.yml$ with a FILE_PATH filter so a pull request cannot change the build commands, keep the buildspec inline or in S3, and split testing (no write permissions) from deployment (trusted actors only) into separate projects with separate roles.

Pull request build policies add a second gate and are enabled by default for new projects. PullRequestBuildPolicy on CreateWebhook/UpdateWebhook has requiresCommentApproval (DISABLED, FORK_PULL_REQUESTS, or the default ALL_PULL_REQUESTS) and approverRoles (GitHub default GITHUB_ADMIN, GITHUB_MAINTAIN, GITHUB_WRITE; GitLab default owner, maintainer, developer). A pull request from an untrusted contributor gets a build status of Failed with the message “Pull request approval required for starting a build” until a trusted contributor comments /codebuild_run(<full-commit-SHA>), after which CodeBuild validates the commenter’s role and runs the build.

Inside a webhook build the trigger is exposed through environment variables: CODEBUILD_WEBHOOK_TRIGGER is pr/<number>, branch/<name> or tag/<name>; CODEBUILD_WEBHOOK_HEAD_REF, CODEBUILD_WEBHOOK_BASE_REF, CODEBUILD_WEBHOOK_EVENT, CODEBUILD_WEBHOOK_ACTOR_ACCOUNT_ID and CODEBUILD_WEBHOOK_PREV_COMMIT carry the rest, and CODEBUILD_SOURCE_VERSION is pr/<number> for a pull request build.

Self-hosted runners. The WORKFLOW_JOB_QUEUED event turns a CodeBuild project into a CodeBuild-hosted GitHub Actions runner: the workflow uses runs-on: codebuild-<project>-${{ github.run_id }}-${{ github.run_attempt }}, optionally with image: and instance-size: label overrides per matrix entry, and CodeBuild only processes workflow jobs when a filter group contains that event. GitLab and Buildkite runners work the same way. Secrets printed by Actions steps are not masked unless the step emits ::add-mask::.

Source Versions, Timeouts, Concurrency and Retries

Source versions. For CodeCommit, GitHub, GHES and Bitbucket you can start a build from a branch name, a commit ID, a tag, a pull request reference (refs/pull/1/head, GitHub and GHES only), or a reference plus commit such as refs/heads/main^{<full-SHA>}. The reference-plus-commit form makes DOWNLOAD_SOURCE faster because CodeBuild downloads only that branch instead of the whole repository to find the commit; a small Git clone depth does the same. S3 sources use the object version ID, and projects can have no source at all.

Timeouts. timeoutInMinutes is 5 to 2,160 minutes (36 hours), default 60; a build that hits it ends with buildStatus: FAILED and the phase that was running shows phaseStatus: TIMED_OUT. queuedTimeoutInMinutes is 5 to 480 minutes (8 hours), default 60, and stops a build that is still queued. Neither can be customised on Lambda compute. Batch builds have their own timeoutInMinutes.

Concurrency. The account has a per-Region concurrent build quota per compute type (the quotas page lists conservative defaults and notes that for some platforms the default is 20; the “Cannot have more than X active builds for the account” error is the signal to request an increase). A project can additionally set concurrentBuildLimit, which cannot exceed the account limit; when the count reaches the limit, new builds are throttled and are not run. Build history is retained for one year, a project can have 5,000 siblings and 50 tags, and a service role can be shared by up to 10 projects.

Retries. retry-build --id <build-id> reruns a single build or a batch. The project-level auto-retry limit (autoRetryLimit) makes CodeBuild call RetryBuild with the project’s service role after a failed build, up to that many additional times; a limit of 2 means up to two extra attempts. Auto-retry is not supported for builds started by CodePipeline. Contrast with the buildspec’s on-failure: RETRY, which is per phase and regex-aware.

Events and metrics. CodeBuild emits EventBridge events with detail types CodeBuild Build State Change and CodeBuild Build Phase Change, publishes CloudWatch metrics (including resource utilisation metrics, which reserved capacity fleets do not support), and can report build status back to the source provider. Build badges are available for every source type except S3.

VPC Builds

By default CodeBuild cannot reach resources in your VPC. Enabling VPC access (VPC ID, up to 16 subnets, up to 5 security groups) lets builds run integration tests against a private RDS database, query ElastiCache, pull from an internal Maven or npm mirror, reach an S3 bucket locked to a VPC endpoint, or present a fixed egress IP through a NAT gateway. The rules the exam tests:

  • Choose private subnets only, with a NAT gateway or NAT instance in a public subnet. An internet gateway alone does not work because CodeBuild cannot assign Elastic IPs or auto-assign public IPs to the network interfaces it creates.
  • Security groups need no inbound rules; outbound must allow whatever the build fetches.
  • Shared VPCs are not supported, local caching is not supported, and Lambda compute cannot join a VPC.
  • VPC endpoints (codebuild, S3, ECR, CloudWatch Logs and so on) let a fully private subnet build without a NAT gateway.

Debugging a Build: codebuild-breakpoint and the Sandbox

Two documented ways exist to see inside a build.

Session Manager. Put the command codebuild-breakpoint in any phase, then start the build with “Enable session connection” (the debugSessionEnabled override); without that option every codebuild-breakpoint and codebuild-resume is ignored. The build pauses at the breakpoint; you connect from the console’s Session Manager link or with aws codebuild batch-get-builds --ids <id> --output json to read sessionTarget and then aws ssm start-session --target <sessionTarget>. Inspect the container, then run codebuild-resume inside it. Prerequisites: the service role needs ssmmessages:CreateControlChannel, CreateDataChannel, OpenControlChannel and OpenDataChannel (plus log permissions if session logging is on); curated Linux images already ship the SSM agent in container mode, a custom image needs SSM Agent 3.0.1295.0 or later plus the amazon-ssm-agent.json container-mode file; Windows and macOS reserved fleets do not support it. Batch tasks opt in with debug-session: true.

CodeBuild sandbox. aws codebuild start-sandbox --project-name <name> launches an interactive environment with the project’s source provider and service integrations, billed per second, where you run commands from the console or connect over SSH from a terminal or IDE. The service role additionally needs ssm:StartSession on the project’s builds and on the AWS-StartSSHSession document. Use the sandbox to iterate on a buildspec without a commit-push-wait loop.

Built-in Environment Variables Worth Knowing

VariableMeaning
CODEBUILD_BUILD_ID / CODEBUILD_BUILD_ARN / CODEBUILD_BUILD_NUMBERIdentity of this build; the number increments per project
CODEBUILD_BUILD_SUCCEEDING1 while succeeding, 0 once failing; guard post_build with it
CODEBUILD_RESOLVED_SOURCE_VERSIONCommit ID (or the CodePipeline revision); unset for S3 sources; available only after DOWNLOAD_SOURCE
CODEBUILD_SOURCE_VERSIONCommit, branch or tag as requested, or pr/<n> for PR webhooks, or the S3 version ID
CODEBUILD_SRC_DIRBuild directory, e.g. /tmp/src123456789/src; _<sourceIdentifier> suffix for secondary sources
CODEBUILD_INITIATORcodepipeline/<pipeline-name> when started by CodePipeline, otherwise the user name
CODEBUILD_KMS_KEY_IDKey used to encrypt the output artifact
CODEBUILD_BUILD_IMAGE, CODEBUILD_START_TIME, CODEBUILD_BUILD_URL, CODEBUILD_PUBLIC_BUILD_URLImage identifier, Unix start time in milliseconds, console URL, public builds URL
HOMEAlways /root

Everything else starting with CODEBUILD_ is internal, and you must not define your own variables with that prefix.

A CodeBuild Lab You Can Run in an Afternoon

  1. Create a project on BUILD_GENERAL1_SMALL with a GitHub source, timeoutInMinutes: 10, queuedTimeoutInMinutes: 5 and an S3 cache with a cacheNamespace.
  2. Reproduce the post_build trap. Put exit 1 in build and a docker push (or just an echo PUSHING) in post_build. Watch POST_BUILD and UPLOAD_ARTIFACTS run anyway, then guard them with CODEBUILD_BUILD_SUCCEEDING.
  3. Add a finally block to pre_build that fails after the main commands succeed and confirm the phase is marked failed.
  4. Retrieve a secret with env/secrets-manager, print it with echo $SECRET | base64, and observe that the encoded form is not masked.
  5. Set the same variable in the buildspec, the project and a start-build --environment-variables-override, and confirm the override wins.
  6. Convert the project to a batch build with a build-matrix of two buildspecs and two variable values; count the four builds, then set fast-fail: true and make one fail. Note that the console asks you for a separate batch service role.
  7. Enable auto-retry with a limit of 1 and compare the two build IDs; then move the project into CodePipeline and observe that auto-retry no longer applies.
  8. Create a reserved capacity fleet with capacity 1 and overflow QUEUE, start two builds at once, and watch the second one wait; switch overflow to ON_DEMAND and watch it run immediately (then delete the fleet, because it bills while idle).
  9. Debug with a breakpoint: add codebuild-breakpoint, start the build with session connection enabled, aws ssm start-session into the container, inspect $CODEBUILD_SRC_DIR, and codebuild-resume.

Scenario Cues → Mechanism

Scenario wordingWhat the exam wants
Image pushed to ECR even though tests failedPOST_BUILD runs after a failed BUILD; guard with CODEBUILD_BUILD_SUCCEEDING
Artifacts uploaded from a failed buildUPLOAD_ARTIFACTS is always attempted
Secret visible in logs after encoding itMasking is exact-match; store the encoded form
Database password must not be visible in consoleparameter-store SecureString or secrets-manager, never env/variables
Buildspec STAGE value “does not apply”start-build override > project > buildspec
Pass the image tag to a later pipeline stageenv/exported-variables + CodePipeline namespace; frozen after post_build
Transient network error should retry only that caseon-failure: RETRY-3-.*connection timed out.* (EC2 on-demand compute only)
Cleanup must run even when commands failfinally block
Build must not run as rootrun-as
Same dependency cache across projects and hostsS3 cache with key, cacheNamespace
Lock-file change should invalidate the cachekey: npm-$(codebuild-hash-files package-lock.json) with fallback-keys
Large Docker images rebuilt constantlyLOCAL_DOCKER_LAYER_CACHE + privileged mode, Linux only
Builds run inside a VPC and caching “stopped working”Local caching unsupported with VPC → use S3 cache
Run tests across six OS/variable combinationsbuild-matrix
Split a 40-minute test suite across machinesbuild-fanout + codebuild-tests-run
Batch build “needs another role”Batch service role for StartBuild/StopBuild/RetryBuild; enforces restrictions
Builds wait minutes to provision; iOS appReserved capacity fleet (macOS is reserved-only)
Reserved fleet bill higher than expectedInstances bill while idle; overflow ON_DEMAND bills separately → QUEUE
Cheapest instance that meets 8 vCPU/32 GiBAttribute-based compute
Fast, short, no Docker, no VPC buildLambda compute (15 min max, no caching, no privileged mode)
Docker build fails “cannot connect to daemon”Enable privileged mode (not Windows; required in VPC builds)
Build only when src/ changes, not docsFILE_PATH filter (first 100 changed files)
Untrusted PRs must not run the pipelinePR build policy ALL_PULL_REQUESTS + /codebuild_run(<sha>); ACTOR_ACCOUNT_ID filter
PR must not alter build commandsInline or S3 buildspec + FILE_PATH exclude ^buildspec.yml$
GitHub Actions jobs should run on CodeBuildWORKFLOW_JOB_QUEUED + runs-on: codebuild-<project>-...
Build stuck “queued” too longqueuedTimeoutInMinutes (5–480) or request concurrency quota
Build killed at 60 minutestimeoutInMinutes default 60, max 2,160
Retry a flaky build automaticallyautoRetryLimit (not for CodePipeline-started builds)
Keep test results longer than 30 daysReport group export to S3
Reproduce a failure interactivelycodebuild-breakpoint + session connection, or the sandbox
Build cannot reach the internet from a private subnetNAT gateway (IGW alone does not work) or VPC endpoints

Common Mistakes

  • Assuming a failed build phase stops the build. post_build and UPLOAD_ARTIFACTS still run. Guard with CODEBUILD_BUILD_SUCCEEDING or move the push into build after the tests.
  • Assuming the buildspec overrides the project. It is the lowest precedence. Overrides belong in start-build or the pipeline action configuration.
  • Printing a transformed secret. Only the exact stored value is masked.
  • Using on-failure on Lambda or reserved capacity. It is silently unsupported there.
  • Reusing the build role for batch builds. It is rejected in spirit by the docs: a separate batch role prevents buildspec-driven build storms and restriction bypasses.
  • Expecting local caches to work in a VPC. They do not; neither does Lambda compute.
  • Forgetting overflow behaviour on a fleet. ON_DEMAND overflow is billed as on-demand builds on top of the always-on fleet.
  • Trusting FILE_PATH on huge pull requests. Only the first 100 changed files are examined; combine with a pull request build policy.
  • Forgetting overrideArtifactName. A build-time artifacts/name is ignored unless semantic versioning is enabled on the project.
  • Relying on auto-retry in a pipeline. Auto-retry does not apply to CodePipeline-initiated builds; use the pipeline’s own retry or the buildspec’s on-failure: RETRY.

How to Practise

Build the lab above once; that fixes the phase diagram and the precedence rules in muscle memory. Then drill scenarios, because the exam never asks “what does finally do”, it asks which of four buildspec changes stops a broken image reaching production. The AWS Certified DevOps Engineer - Professional (DOP-C02) Mock Exam Bundle has eight 75-question timed exams whose explanations name the phase, the precedence level, the cache mode or the fleet setting a scenario hinges on, which is exactly the kind of distinction this exam uses to separate “has used CodeBuild” from “understands CodeBuild”. Pair it with our DOP-C02 practice questions and the CI/CD guide for the surrounding pipeline, and with the Developer Associate CI/CD guide if you want the associate-level basics first.

Frequently Asked Questions

Does the post_build phase run if the build phase fails?

Yes. According to the phase transition rules, a failure in BUILD continues to POST_BUILD, then UPLOAD_ARTIFACTS, then FINALIZING; only failures in PROVISIONING, DOWNLOAD_SOURCE, INSTALL or PRE_BUILD jump straight to FINALIZING. Use CODEBUILD_BUILD_SUCCEEDING (0 when failing) to skip pushes and deployments in post_build.

What is the order of precedence for CodeBuild environment variables?

The start-build call (override) has the highest precedence, then the project definition, then the buildspec declaration. Variables retrieved from Parameter Store or Secrets Manager replace any existing variable of the same name, and names beginning with CODEBUILD_ are reserved.

Why did my secret appear in the CodeBuild logs?

CodeBuild masks only the exact value stored in Parameter Store or Secrets Manager. Base64-encoding, reversing, changing the case of, or concatenating the secret produces a different string that is not masked. Store the value in the form the build uses, and never place secrets in env/variables.

What is the difference between on-failure RETRY and the project auto-retry limit?

on-failure: RETRY is a per-phase buildspec setting that retries the build (up to 3 times by default, or RETRY-count, optionally only when the error matches a regex) and works only with EC2 on-demand compute. The project autoRetryLimit makes CodeBuild call RetryBuild after any failed build, up to the limit, and does not apply to builds started by CodePipeline.

When should I use S3 caching versus local caching?

Use S3 caching when the cache must be shared across build hosts or projects (cacheNamespace), when builds run in a VPC, or when dependencies are small to medium. Use local caching (LOCAL_SOURCE_CACHE, LOCAL_DOCKER_LAYER_CACHE with privileged mode on Linux, or LOCAL_CUSTOM_CACHE for directories) for frequent builds with large artifacts; local caching is unsupported with VPC, LINUX_GPU_CONTAINER and BUILD_GENERAL1_2XLARGE.

Why do batch builds need a separate service role?

Because CodeBuild must call StartBuild, StopBuild and RetryBuild to run the batch. Giving those permissions to the normal build role would let a buildspec start more builds and bypass the batch restrictions on the maximum number of builds, allowed compute types and allowed fleets.

What are the limitations of Lambda compute in CodeBuild?

No root tools (yum, rpm), no Docker builds or runs, writes only under /tmp, no GPU or Windows, no caching, no custom build or queue timeouts, no build badges, no privileged mode, no custom runtime environments, a 15-minute maximum runtime, no VPC connectivity, no fixed source IPs, no EFS, no certificates and no Session Manager. Use EC2 compute when any of these matter.

How does overflow behavior work on a reserved capacity fleet?

Capacity defines how many builds run in parallel on the always-on instances. With overflow set to on-demand, extra builds run on CodeBuild on-demand and are billed separately; with queue, extra builds wait until a fleet instance is free, which limits cost. Attribute-based configurations that are unavailable on-demand fall back to queue behaviour.

How do webhook filter groups decide whether to start a build?

A build starts if any filter group evaluates to true, and a group is true only when every filter in it matches. Filters are RE2 regular expressions on HEAD_REF, BASE_REF (pull requests only), FILE_PATH (first 100 changed files), COMMIT_MESSAGE, ACTOR_ACCOUNT_ID, TAG_NAME, RELEASE_NAME, REPOSITORY_NAME, ORGANIZATION_NAME or WORKFLOW_NAME, and any filter can be negated with excludeMatchedPattern.

What is a CodeBuild pull request build policy?

A webhook setting, enabled by default on new projects, that requires comment approval before building pull requests from contributors who are not in the approver roles (ALL_PULL_REQUESTS by default, or FORK_PULL_REQUESTS, or DISABLED). An untrusted PR shows a Failed status until a trusted contributor comments /codebuild_run(<commit-SHA>).

What are the default and maximum build timeouts?

The build timeout defaults to 60 minutes and can be set between 5 and 2,160 minutes (36 hours). The queued timeout also defaults to 60 minutes with a range of 5 to 480 minutes (8 hours). A timed-out build has buildStatus FAILED and the running phase shows TIMED_OUT. Lambda compute does not support custom timeouts.

How do I pause a CodeBuild build and inspect the container?

Add codebuild-breakpoint to a phase, start the build with “Enable session connection” (otherwise the breakpoint is ignored), connect through the Session Manager link or aws ssm start-session --target <sessionTarget> from batch-get-builds, and run codebuild-resume when done. The service role needs the four ssmmessages:* channel permissions. Alternatively start a sandbox with start-sandbox for an interactive, per-second-billed environment.

Conclusion

CodeBuild questions on the DOP-C02 are mechanism questions dressed as pipeline scenarios. The phase diagram explains the broken image in ECR; the precedence list explains the override that “did not apply”; exact-match masking explains the leaked secret; finally and on-failure explain how to retry and clean up without a wrapper script. Batch builds add a second role and four coordination patterns, caching splits into a shared S3 cache with hashed keys and three host-local modes that do not survive a VPC, and compute splits into disposable on-demand machines, always-billing reserved fleets with overflow rules, and a Lambda mode whose limitation list is the exam material. Webhook filter groups are AND-within-OR with a 100-file limit, pull request policies gate untrusted contributors, timeouts run 5 to 2,160 minutes, auto-retry skips pipeline builds, and codebuild-breakpoint turns a black box into a shell. Learn these as rules, run the lab once, and the CodeBuild scenario on exam day becomes one you have already debugged.

Limited Time Offer: Get 80% off all Mock Exam Bundles | Sale ends in 7 days. Start learning today.

Claim Now