CodeBuild uses a build environment image for its tools and a buildspec for its commands. These sections explain phase execution, secrets, reports, caching, private network access, and outputs for later pipeline actions.
Buildspec phases
A CodeBuild buildspecA buildspec is a YAML document containing the commands and settings for a build. is a YAMLYAML is the structured text format used to express a CodeBuild buildspec. file, a text format for structured settings, that tells the build environmentA build environment combines an operating system, language runtime, and tools used to run build commands. which commands to run. The environment image supplies the operating system, language runtimeA runtime provides the language environment selected for running build software., and tools; the buildspec supplies the recipe.
How it works
- Select a CodeBuild-provided image or an accessible custom image from ECR or Docker Hub.
- Load
buildspec.ymlfrom the source root, or choose a project or build override. An inline project buildspec is also supported. An S3 buildspec uses its object ARNAn ARN is an identifier that names an AWS resource., the AWS resource identifier, and a bucket in the project Region. - Run the configured phases in order. Use
installto install packages,pre_buildto prepare,buildto compile or test, andpost_buildto package or publish. - Run each phaseA phase is a named stage of build execution with its own commands and result.’s
finallyblock after its commands, including when a command fails.
Exam cues
- If the question says a directory change disappears between CodeBuild commands, think buildspec version
0.2, because version0.1isolates commands in separate shellsA shell executes command text and holds command state such as the current directory.. - If the question says a build needs a custom compiler environment, think a custom ECR image, because the image supplies the tools used by the buildspec.
- If the question says one repository needs a different build recipe for a particular run, think
buildspecOverride, because it selects that build’s alternate file.
Remember
- Default file:
buildspec.ymlat the source root. - Phase order:
install,pre_build,build,post_build. - S3 buildspec bucket: same Region as the project.
- A project specifies one buildspec.
Trap: A
finallyblock belongs to its phase. It can run after that phase’s command fails; it is not a replacement for the phase order.
Finish installation before preparation.
Run build or test commands after preparation.
Run post-build commands after the build.
From the AWS docs (16)
- A buildspec is a YAML document containing build commands and settings.
- The default source buildspec is buildspec.yml in the source root.
- The project buildspec setting can select another source-relative file.
- StartBuild buildspecOverride can select another source-relative file for a build.
- An S3 buildspec is specified by object ARN and its bucket must be in the project Region.
- A project specifies one buildspec.
- A buildspec can be defined in the project rather than included in source.
- The buildspec phase order is install, pre_build, build, post_build.
- The install phase installs packages needed by the build.
- The pre_build phase runs preparation commands such as signing in to ECR.
- The build phase runs build or test commands.
- The post_build phase runs commands after the build, such as packaging or pushing an image.
- Buildspec version 0.1 isolates each command in a separate shell; version 0.2 resolves that state-sharing limitation.
- A phase runs its finally commands even if a command in its commands block fails.
- A build environment combines an operating system, language runtime, and tools in a Docker image.
- Build images can come from the CodeBuild image repository, Docker Hub, or accessible ECR repositories.
Exit codes and failure handling
CodeBuild handles command failures at the build phaseA phase is a named stage of build execution with its own commands and result. level. An exit statusAn exit status is the result returned by a command and included in build error context when available. is the result a command returns to its caller; a check can return a failing status to reject a build.
How it works
- Run the phase’s commands. If a command fails, skip the remaining commands in that block and run the phase’s
finallyblock. - Apply the phase’s
on-failurebehavior when configured. The phase succeeds only if its normal and cleanup commands succeed. - Read
CODEBUILD_BUILD_SUCCEEDINGwhen a command needs the current build result:1means succeeding and0means failing. - Attempt
UPLOAD_ARTIFACTSeven ifBUILDfailed, so failure does not prevent an artifactAn artifact is a set of files passed between actions in a pipeline. upload attempt. - To retry a failed build rather than a phase, set the automatic retry limit for the build. A StartBuild override applies only to that request.
- For CodePipeline builds, use stage retry instead. CodeBuild automatic build retry does not support CodePipeline.
| Phase setting | Failure behavior |
|---|---|
ABORT |
Stop the build. |
CONTINUE |
Continue to the next phase. |
RETRY |
Retry up to 3 times for any error. |
RETRY-count |
Set a count from 0 through 100. |
RETRY-regex |
Retry up to 3 times for a matching error pattern. |
RETRY-count-regex |
Set both count and matching error pattern. |
A regular expressionA regular expression is a text pattern used to match error messages or webhook fields., or regex, is a text pattern used here to match error messages.
Exam cues
- If the question says failed tests must stop CodeBuild, think a test command that returns failure and
ABORT, because a failed command fails its phase and the policy stops the build. - If the question says a temporary error should retry but other errors should not, think
RETRY-count-regex, because it matches the error text and bounds the retries. - If the question says cleanup must run after a failed command, think
finally, because the rest of the normal command block is skipped. - If the question says a failed build should start again, think the automatic build retry limit, because phase retry controls a phase rather than the whole build.
- If the question says a failed CodePipeline build needs automatic retry, think CodePipeline stage retry, because CodeBuild automatic build retry does not support CodePipeline.
Remember
RETRY: up to 3 retries. An explicit count can be 0 through 100.on-failurerequires CodeBuild-provided EC2 compute images; Lambda compute and reserved capacity do not support it.UPLOAD_ARTIFACTSis attempted after aBUILDfailure.- An automatic retry limit of 2 permits up to 2 additional builds.
- CodeBuild automatic build retry uses the project service roleA service role is an IAM role that a service uses to perform authorized operations on your behalf. and does not support CodePipeline.
Trap: A report file is evidence to inspect. Make the test or coverage check return failure when the release requirement is unmet, and choose a failure policy that stops the build.
From the AWS docs (15)
- A failed command makes its phase fail.
- After a commands-block failure, remaining commands in that block are skipped and finally commands still run.
- A phase succeeds only when its commands and finally commands all succeed.
- Phase on-failure ABORT aborts the build.
- Phase on-failure CONTINUE proceeds to the next phase.
- RETRY retries up to 3 times and matches any error message.
- RETRY-count accepts a retry count from 0 through 100.
- RETRY-regex retries up to 3 times for matching errors; RETRY-count-regex sets both the count and error pattern.
- on-failure works only with CodeBuild-provided EC2 compute images, not Lambda compute or reserved capacity.
- CODEBUILD_BUILD_SUCCEEDING is 1 when the build is succeeding and 0 when it is failing.
- UPLOAD_ARTIFACTS is attempted even when BUILD fails.
- A build check can fail a CodeBuild build by returning exit code 1, as in the AWS container-scanning example.
- StartBuild can override the automatic retry limit for a failed build; a limit of 2 permits up to 2 additional builds through RetryBuild.
- CodeBuild automatic build retry uses the project service role and is not supported for CodePipeline.
- CodePipeline can retry a failed stage or failed actions in that stage, including through one automatic stage retry attempt.
Environment variables and secrets
CodeBuild maps environment variableAn environment variable is a named value available to build commands. names to plain values or stored secrets. An environment variable is a named value available to build commands. Secret references let the build retrieve a value without putting it in the buildspecA buildspec is a YAML document containing the commands and settings for a build. text.
How it works
- Choose a mapping under
env. Use plainvariablesfor non-sensitive values,parameter-storefor parameter names, orsecrets-managerfor secret references. - Grant the service roleA service role is an IAM role that a service uses to perform authorized operations on your behalf., the AWS permission identity used by CodeBuild,
ssm:GetParametersorsecretsmanager:GetSecretValue. Decrypting a Parameter StoreSecureString, an encrypted parameter value, requireskms:Decrypt; Secrets Manager reads under a customer managed KMS key also require it. - For Secrets Manager, use
secret-id:json-key:version-stage:version-id. A JSON key selects one named field; omitting it retrieves the whole secret text. Use an ARNAn ARN is an identifier that names an AWS resource., an AWS resource identifier, for another account’s secret. - Resolve duplicate variable names by precedence: StartBuild request, project, then buildspec. Treat logging separately: a transformed secret can escape masking.
| Mapping | Value supplied in the buildspec | Use |
|---|---|---|
variables |
Plain text | Non-sensitive settings. |
parameter-store |
Parameter name | Retrieve a stored parameter. |
secrets-manager |
Secret reference | Retrieve a secret or one JSON field. |
Exam cues
- If the question says a token is visible in the CodeBuild console, think a secret reference, because plain variables can be displayed in the console and CLI.
- If the question says a secret is readable but its transformed value appears in logs, think exact-value masking, because transformations produce a different string.
- If the question says a build override changes a project variable, think StartBuild precedence, because request values have the highest priority.
Remember
- Default secret version:
AWSCURRENT. - Specify a version stage or version ID, not both.
CODEBUILD_is reserved for CodeBuild.- Mappings replace existing values literally, including
$PATHtext.
Trap: Masking is not permission to print secrets. A Base64 transformation can appear in logs even when the original stored value is masked.
From the AWS docs (16)
- Plain environment variable values can be displayed in the console and AWS CLI.
- env.parameter-store maps build variable names to Parameter Store parameter names.
- The CodeBuild service role needs ssm:GetParameters to retrieve Parameter Store values.
- env.secrets-manager uses secret-id:json-key:version-stage:version-id references.
- Omitting json-key retrieves the entire secret text.
- A Secrets Manager mapping retrieves AWSCURRENT when no version stage or version ID is specified.
- Specify a version stage or version ID, not both.
- A secret in another account must be referenced by its ARN.
- GetSecretValue requires secretsmanager:GetSecretValue and kms:Decrypt when the secret uses a customer managed KMS key.
- StartBuild values override project values, which override buildspec values.
- Secret masking matches stored values exactly; transformations such as Base64 can expose a different value in logs.
- CODEBUILD_ is reserved and must not prefix user-defined variable names.
- Variable mappings replace existing values literally, so a mapped PATH containing $PATH does not expand the old PATH.
- Decrypting a Parameter Store SecureString requires kms:Decrypt permission for its KMS key.
- CODEBUILD_RESOLVED_SOURCE_VERSION holds the commit ID that was built, while CODEBUILD_SOURCE_VERSION holds the version requested, such as a branch name or commit ID.
- CODEBUILD_INITIATOR names who started the build; when the CodeBuild plugin for Jenkins starts it, the value is CodeBuild-Jenkins-Plugin.
Test and coverage reports
CodeBuild reports collect files produced by test tools. A report groupA report group collects report runs and shares settings such as permissions and export configuration. holds report runs and shared settings such as export permissions. Code coverage measures how much code the tests exercise.
How it works
- Run tests or coverage analysis in build commands. Coverage commands can run in
buildorpost_build. - Configure
reports.filesto locate the result files and select the matchingfile-format. - Supply a report group name to create a group, or an existing group’s ARNAn ARN is an identifier that names an AWS resource., its AWS resource identifier, to reuse it. Each build adds a report.
- Configure the group’s S3 export if raw files must remain after the report expires. Grant the project service roleA service role is an IAM role that a service uses to perform authorized operations on your behalf. permission to upload them.
| Result type | Accepted formats | Meaning |
|---|---|---|
| Tests | JUnit XML, Cucumber JSON, NUnit XML, NUnit3 XML, TestNG XML, Visual Studio TRX or TRX XML | Results produced by the test framework. |
| Line coverageLine coverage measures the statements exercised by tests. | JaCoCo XML, Cobertura XML, Clover XML, SimpleCov JSON, LCOV INFO | Statements exercised by tests. |
| Branch coverageBranch coverage measures the control-flow branches exercised by tests. | JaCoCo XML, Cobertura XML, Clover XML, SimpleCov JSON, LCOV INFO | Branches exercised in control structures. |
Exam cues
- If the question says results must be retained beyond 30 days, think report group S3 export, because the report view expires but raw exported files do not have that expiry.
- If the question says several builds must use an existing report group, think its ARN, because a buildspecA buildspec is a YAML document containing the commands and settings for a build. name creates a group.
- If the question says line coverage looks good but conditional paths are untested, think branch coverage, because it measures branches of control structures.
Remember
- Maximum: 5 report groups per project.
- Test report lifetime: 30 days after creation.
- Default report format:
JUNITXML. - SimpleCov input comes from
simplecov, notsimplecov-json.
Trap: Exporting raw files to S3 preserves those files. It does not make an expired CodeBuild report viewable again.
From the AWS docs (14)
- Supported test formats are JUnit XML, Cucumber JSON, NUnit XML, NUnit3 XML, TestNG XML, and Visual Studio TRX or TRX XML.
- The default report file-format is JUNITXML.
- A report group holds reports with shared settings such as export configuration and permissions.
- A build project can specify up to 5 report groups.
- A buildspec report group name creates a group; an ARN selects an existing group.
- reports.files identifies the generated test result files to collect.
- Each build run creates a new report in its configured report group.
- A test report expires 30 days after creation and cannot then be viewed.
- A report group can export raw result files to S3; those files do not have CodeBuild report expiry.
- The project service role supplies permissions to upload report exports to S3.
- Coverage formats are JaCoCo XML, Cobertura XML, Clover XML, SimpleCov JSON, and LCOV INFO.
- Line coverage measures covered statements; branch coverage measures covered control-flow branches.
- SimpleCov coverage input must come from simplecov, not simplecov-json.
- Coverage analysis commands run in the build or post_build phase and generate files for reports.
Artifacts and exported variables
CodeBuild artifactsAn artifact is a set of files passed between actions in a pipeline. are output files selected for later use. Exported variables pass named values between CodePipeline actions. Use artifacts for the files and variables for values such as a version identifier.
How it works
- Select output files with
artifacts.files. Usebase-directoryto select their parent directory anddiscard-pathsto flatten directory paths if required. - Declare the CodeBuild action outputs in CodePipeline. CodePipeline stores artifacts in its S3 artifact bucket. Later actions take those outputs as inputs. With multiple inputs, set
PrimarySourceto the artifact containing the buildspecA buildspec is a YAML document containing the commands and settings for a build.; each input is extracted separately. - For multiple outputs, define every output under
secondary-artifactsand match each identifier to its CodePipeline output name. Include the top-levelartifacts.filessequence even when only secondary artifacts are defined. - List values under
env.exported-variables. Give the action a namespaceA namespace groups the output variables of a pipeline action so later actions can reference them., a name grouping its output variables, and read them later with#{namespace.variable}. - Authorize artifact encryption. CodeBuild needs KMS key access; a customer managed key requires an appropriate key policyA key policy controls access to a KMS key used for artifact encryption..
- For standalone S3 output, choose
ZIPpackaging or an uncompressed folder and optionally includeBUILD_IDin the path. EnableoverrideArtifactNameto use the buildspec name. CodePipeline manages its own output location and packaging.
Exam cues
- If the question says one build must produce separate packages for later actions, think secondary artifacts, because output identifiers map each bundle to a pipeline output.
- If the question says a later action needs a build version, think an exported variable and namespace, because CodePipeline can resolve the value during execution.
- If the question says an S3 upload fails on encryption, think KMS key access, because writing an object and using its encryption key require separate authorization.
- If an explicit proxy blocks artifact upload, set
proxy.upload-artifactstoyes, because the default isno. - If a CodePipeline batch build needs one output, enable
BatchEnabledandCombineArtifacts. - If a CodeDeploy action in another account needs a pipeline artifact, configure role trust and bucket and customer managed KMS key access. Artifacts cannot pass directly between two non-pipeline accounts.
- If upload reports an invalid ARNAn ARN is an identifier that names an AWS resource., check that the S3 output bucket and CodeBuild project are in the same Region.
- If the question says verify a CodeBuild artifact with the hash CodeBuild reports, think ZIP packaging, because the hashes exist only for ZIP artifacts.
Remember
- CodePipeline CodeBuild action: 1 to 5 input artifacts and 0 to 5 output artifacts.
- Export values can change from
installthrough the end ofpost_build. - Project-configured Parameter Store and Secrets Manager secrets cannot be exported. Variables starting
AWS_cannot be exported. - Default artifact encryption key: the account’s AWS managed key for S3.
- Standalone S3 artifacts default to an uncompressed folder and no build ID in the path.
- CodeBuild attempts artifact upload even when the build phaseA phase is a named stage of build execution with its own commands and result. fails.
Trap: Defining several pipeline output names is insufficient. Each must match an identifier in the buildspec’s secondary artifacts.
Select output files in the buildspec.
Export named values through the action namespace.
A later action consumes the output artifact.
A later action references the namespaced value.
From the AWS docs (23)
- artifacts.files selects output files; base-directory selects their parent directory and discard-paths controls directory flattening.
- CodeBuild output artifacts can be inputs to subsequent CodePipeline actions.
- With multiple CodePipeline outputs, all outputs must be secondary artifacts whose identifiers match the action output names.
- A CodePipeline CodeBuild action accepts 1 to 5 inputs and 0 to 5 outputs.
- env.exported-variables lists container variables to pass to subsequent CodePipeline stages.
- A CodePipeline namespace groups the output variables of an action; later actions reference them as #{namespace.variable}.
- Exported variable values can change from install through the end of post_build, then become fixed.
- Project-configured Parameter Store secrets, project-configured Secrets Manager secrets, and variables starting AWS_ cannot be exported.
- CodeBuild needs KMS key access to encrypt output artifacts and by default uses the account AWS managed key for S3.
- A customer managed key must have a key policy allowing the required use by CodeBuild.
- CodePipeline stores action input and output artifacts in its S3 artifact bucket.
- A CodeBuild action with multiple input artifacts requires PrimarySource; CodeBuild reads its buildspec from that input and extracts each input to a separate directory.
- For S3 output, CodeBuild defaults to an uncompressed folder; ZIP packaging is an option. CodePipeline manages its own output location and packaging.
- For S3 output, namespaceType defaults to NONE; BUILD_ID includes the build ID in the output path.
- The overrideArtifactName project flag lets a buildspec name override the configured artifact name.
- Builds using an explicit proxy must set proxy.upload-artifacts to yes to upload artifacts; the default is no.
- A cross-account CodePipeline setup requires access to the artifact bucket and a customer managed KMS key, plus a trusted cross-account role; an artifact cannot pass directly between two non-pipeline accounts.
- CombineArtifacts combines artifacts from a CodePipeline batch build into one output and requires BatchEnabled.
- The top-level artifacts.files sequence is required even if the buildspec defines only secondary artifacts.
- CodeBuild always attempts the UPLOAD_ARTIFACTS phase even if the BUILD phase fails.
- A CodeBuild S3 output bucket in a different Region from the project can cause an invalid ARN error during artifact upload.
- CodeBuild reports the SHA-256 and MD5 hashes of a build artifact only when the project packaging is ZIP.
- A CodeBuild build's artifacts expose a SHA-256 hash for integrity checks only when the project's artifact packaging is ZIP.
Build caching
CodeBuild caching reuses build components so later runs can avoid repeated work. A cacheA cache stores build components for reuse in later builds. is stored data that a later build can reuse. Choose S3 caching for reuse across hosts or local caching for reuse on the same host.
How it works
- Select S3 or local caching on the project. S3 stores cached files in a bucket; local caching stores them on the build host.
- Set
cache.pathsfor S3 files or custom local directories. Local source and Docker modes cache their specific data. - For versioned S3 caches, select a
key. Each key identifies an immutable cache copy; change the key to create another copy. - To share an S3 cache across projects, match
cacheNamespace, key, paths, bucket, andpathPrefixif configured.
| Local mode | Cached content | Constraint |
|---|---|---|
| Source | Git metadata | Helps retrieve changes between commits. |
| Docker layerA Docker layer is a reusable part of a container image that local Docker caching can retain. | Existing image layers | Requires Linux and privileged modePrivileged mode grants the Docker permissions required for VPC Docker builds and local Docker layer caching.. |
| Custom | Listed directories | Individual files are unsupported. |
Exam cues
- If the question says builds run on different hosts, think S3 cache, because a local cache is available only on its own host.
- If the question says a VPCA VPC is a virtual network isolated from other virtual networks in AWS. build needs cached dependencies, think S3 cache, because VPC builds cannot use local caching.
- If the question says projects must reuse the same S3 cache, think matching namespaceA namespace groups the output variables of a pipeline action so later actions can reference them., key, paths, and S3 location, because those settings determine sharing.
Remember
- Local caching is unsupported for VPC builds and is less useful for infrequent builds.
- Local Docker layer cache requires Linux and privileged mode.
- Local custom cache supports directories only.
- Matching local cache and source directory names can overwrite source contents.
Trap: A local Docker layer cache is not shared storage. Another build host cannot use that host’s cache.
From the AWS docs (11)
- CodeBuild caches reusable build components to avoid rebuilding or downloading them on later runs.
- An S3 cache is available across multiple build hosts.
- cache.paths selects files for S3 caching.
- A cache key selects an immutable cache copy; changing the key creates a new cache.
- Cross-project S3 cache sharing requires matching cacheNamespace, key, paths, bucket, and pathPrefix if set.
- A local cache is available only on the host where it is stored and is less useful for infrequent builds.
- Local source cache stores Git metadata so later downloads can retrieve changes between commits.
- Local Docker layer cache reuses image layers and requires Linux and privileged mode.
- Local custom cache stores buildspec-listed directories, not individual files.
- Local custom cache links directories before source download; matching cache names can overwrite source directories.
- Local caching is unsupported for VPC builds.
VPC builds
A VPC-enabled CodeBuild project lets build commands reach private resources such as an RDS database. A VPCA VPC is a virtual network isolated from other virtual networks in AWS. is an isolated AWS network; a subnetA subnet is a range of IP addresses within a VPC. is a range of addresses within it. Configuring the VPC connects the build to that network.
How it works
- Set the project’s VPC ID, private subnet IDs, and security groupA security group controls traffic allowed to and from associated resources. IDs. A security group controls allowed network traffic.
- Allow the outbound traffic the build needs. The build security group does not need inbound rules.
- For internet downloads, route traffic through a NATNAT provides outbound internet access for VPC build interfaces without public IP addresses. gateway in a public subnet. NAT provides an outbound path for resources without public IP addresses.
- For S3 access without NAT, associate an S3 gateway endpointA gateway endpoint adds a route to a supported AWS service without requiring a NAT device. with the route table used by the build subnet. The endpoint provides a private route to S3, not a route to the general internet.
Exam cues
- If the question says tests must reach private RDS, think a VPC-enabled CodeBuild project, because the project subnet and security group settings provide private resource access.
- If the question says a public-subnet build cannot download internet packages, think private subnets plus NAT, because CodeBuild network interfaces have no public IP addresses.
- If the question says only S3 downloads need a route without NAT, think an S3 gateway endpoint, because it routes S3 traffic through the subnet route table.
Remember
- CodeBuild interfaces cannot receive public or Elastic IP addresses.
- NAT gateways belong in public subnets; CodeBuild should use private subnets.
- S3 gateway endpoints have no additional charge and must be in the bucket Region.
- Shared VPC connectivity and local caching are unsupported.
Trap: An internet gateway alone does not give a CodeBuild network interface internet access. It lacks the public address needed for that path.
Run integration tests against the private database.
Send internet traffic through NAT in a public subnet.
NAT supplies the outbound internet path.
From the AWS docs (11)
- A VPC-enabled project specifies the VPC, subnet IDs, and security group IDs to reach private resources.
- VPC builds can run integration tests against RDS in private subnets.
- AWS recommends private subnets for CodeBuild builds.
- Internet access requires a NAT gateway or NAT instance; a NAT gateway belongs in a public subnet.
- CodeBuild-created network interfaces cannot receive public or Elastic IP addresses, so an internet gateway alone does not provide internet access.
- Build security groups need no inbound rules and must allow required outbound traffic.
- CodeBuild VPC connectivity does not support shared VPCs.
- An S3 gateway endpoint routes S3 traffic through an associated route table without NAT and has no additional charge.
- An S3 gateway endpoint must be in the same Region as the bucket.
- VPC builds cannot use local caching.
- S3 caching provides a cache available across build hosts.
Pull request builds
CodeBuild repository webhooksA webhook delivers repository event information that CodeBuild can filter to start a build. start builds in response to source events. A webhook is an event notification sent by the repository provider. Pull requestA pull request proposes source branch changes for review before merging. builds run tests on proposed changes, while comment approval controls whether untrusted contributions may execute.
How it works
- For GitHub pull requests, filter for
PULL_REQUEST_CREATEDandPULL_REQUEST_UPDATED. Every filter within a group must match; any matching group can qualify. - Apply the pull request build policy. Trusted contributors build automatically; untrusted contributions need a trusted role holder’s approval comment for the latest commit.
- Until approved, the build is marked Failed. The trusted contributor posts
/codebuild_run(<latest-commit-SHA>), and CodeBuild checks permissions before starting the build and reporting results on the pull request. - Limit the build role’s permissions. AWS recommends separate test and deployment projects, trusted-actor filters for deployment, and an inline or S3 buildspecA buildspec is a YAML document containing the commands and settings for a build. that pull requests cannot edit.
| Comment approval setting | Contributions requiring approval |
|---|---|
DISABLED |
None. |
FORK_PULL_REQUESTS |
ForkA fork is a copy of a repository used to propose changes back to the original repository. contributions from untrusted contributors. |
ALL_PULL_REQUESTS |
All pull requests from untrusted contributors. |
For CodeCommit, use its pullRequestCreated and pullRequestSourceBranchUpdated EventBridge events with a CodeBuild project target. CodeCommit is outside the documented CodeBuild repository webhook provider list.
Exam cues
- If the question says run tests before a GitHub pull request merges, think pull request webhook events, because they cover opened and updated proposals.
- If the question says unknown contributors must be reviewed first, think comment approval, because untrusted changes do not start a build until a trusted role holder approves the commit.
- If the question says a public test project has deployment permissions, think separate projects and roles, because webhook code runs with the project’s service roleA service role is an IAM role that a service uses to perform authorized operations on your behalf..
Remember
- New projects enable comment approval by default with
ALL_PULL_REQUESTS. ACTOR_ACCOUNT_IDfilters identify permitted webhook senders.- For GitHub and GitHub Enterprise Server PR webhooks,
CODEBUILD_SOURCE_VERSIONispr/<pull-request-number>.
Trap: A protected buildspec does not grant trust to pull request code. Keep the test role’s permissions limited and require approval where contributor code is untrusted.
Match pull request creation or source branch update events.
Target a CodeBuild project with the matching rule.
From the AWS docs (14)
- CodeBuild supports repository webhooks for GitHub, GitHub Enterprise Server, GitLab, GitLab Self Managed, and Bitbucket.
- GitHub PULL_REQUEST_CREATED and PULL_REQUEST_UPDATED webhook events cover newly opened and updated pull requests.
- All filters in a webhook group must match; matching any group can trigger the build.
- ACTOR_ACCOUNT_ID filters restrict webhook builds by sender account identifier.
- An inline or S3 buildspec prevents pull requests from changing the project buildspec.
- AWS recommends separate webhook test and deployment projects, with no resource write permissions on the test role and trusted-user filters on deployment.
- With comment approval enabled, trusted contributors build automatically; untrusted contributions need a trusted role holder to comment /codebuild_run(<latest-commit-SHA>).
- An unapproved pull request build is marked Failed until a valid approval triggers the build; results appear on the pull request.
- New projects enable pull request build policy by default with ALL_PULL_REQUESTS.
- DISABLED removes comment approval; FORK_PULL_REQUESTS requires it for forks; ALL_PULL_REQUESTS applies it to all pull requests except trusted contributors.
- For GitHub and GitHub Enterprise Server webhook pull requests, CODEBUILD_SOURCE_VERSION is pr/<pull-request-number>.
- CodeCommit emits pullRequestCreated and pullRequestSourceBranchUpdated events to EventBridge.
- An EventBridge rule can target a CodeBuild project.
- With build status reporting turned on, CodeBuild posts the build result to the commit or pull request in the source provider.
Container image builds
CodeBuild can build a Docker image and publish it to ECR. An image packages software for running in a container; ECR stores that image in a repository. Build commands explicitly authenticate, build, tag, and push it.
How it works
- Select an image with the Docker tools needed for the build. AWS also documents a custom build imageA container image supplies the software environment in which build commands run. example using
docker:dindfrom Docker Hub. - Ensure the Docker daemonThe Docker daemon is the process used to build and run Docker containers., the process that builds and runs containers, is available. AWS documents it as enabled by default for non-VPC builds. Enable privileged modePrivileged mode grants the Docker permissions required for VPC Docker builds and local Docker layer caching. for VPCA VPC is a virtual network isolated from other virtual networks in AWS. Docker builds; that mode grants the required Docker permissions.
- In
pre_build, authenticate to ECR usingaws ecr get-login-passwordwithdocker login. - In
build, rundocker buildanddocker tag. Inpost_build, rundocker pushto publish to ECR.
Exam cues
- If the question says the image exists locally but is absent from ECR, think
docker push, because building and publishing are separate commands. - If the question says ECR login succeeds but image upload is denied, think the role’s ECR upload permissions, because obtaining an authorization token is only part of publishing.
- If the question says Docker fails inside a VPC build, think privileged mode and daemon availability, because VPC Docker builds need that configuration.
Remember
- ECR publishing permissions:
GetAuthorizationToken,BatchCheckLayerAvailability,InitiateLayerUpload,UploadLayerPart,CompleteLayerUpload, andPutImage, all underecr:. - Docker layerA Docker layer is a reusable part of a container image that local Docker caching can retain. caching requires Linux and privileged mode.
- Windows does not support privileged mode.
Trap: Do not confuse the build environmentA build environment combines an operating system, language runtime, and tools used to run build commands. image with the image your commands produce. The environment supplies tools;
docker pushpublishes the resulting application image.
Authenticate before building and tagging the image.
Push the tagged image to ECR in post_build.
From the AWS docs (8)
- The Docker sample builds an image and pushes it to an ECR repository using build commands.
- The sample signs in with aws ecr get-login-password piped to docker login during pre_build.
- The sample runs docker build and docker tag in build and docker push in post_build.
- ECR publishing needs ecr:GetAuthorizationToken, ecr:BatchCheckLayerAvailability, ecr:InitiateLayerUpload, ecr:UploadLayerPart, ecr:CompleteLayerUpload, and ecr:PutImage.
- The Docker daemon is enabled by default for non-VPC builds; VPC Docker builds need privileged mode.
- Docker layer caching requires Linux and privileged mode.
- The AWS custom-image sample uses docker:dind from Docker Hub to build and run an image.
- Windows does not support privileged mode.
Service role and troubleshooting
The CodeBuild service roleA service role is an IAM role that a service uses to perform authorized operations on your behalf. is the permission identity used for operations CodeBuild performs on your behalf. Troubleshooting starts by finding the failed phaseA phase is a named stage of build execution with its own commands and result., then checking its commands, permissions, and network access.
How it works
- Allow
codebuild.amazonaws.comto assume the service role through its trust policyA trust policy specifies which principals may assume an IAM role., the policy naming who may use the role. Grant only the required permissions. - Open the build details in the console or call
BatchGetBuilds. Inspect phase type, status, and error context alongside CloudWatch Logs or S3 logs. - For S3 reads, inspect
s3:GetObjectands3:GetObjectVersionon the required objects. If the bucket requiresaws:sourceVpce, use that permitted VPCA VPC is a virtual network isolated from other virtual networks in AWS. endpoint. For CloudWatch logging, inspectlogs:CreateLogGroup,logs:CreateLogStream, andlogs:PutLogEvents. - Use CloudWatch metrics to study recurring failures or duration changes. Use
ProjectName, a metric filter identifying the project, for project metrics; omit dimensions for account metrics. - To reproduce build commands locally, use the CodeBuild local agent with Git, Docker, the build imageA container image supplies the software environment in which build commands run., and the local build script.
- For a shared project, a CodePipeline action can override its service role with a role in the project account. The pipeline editor and pipeline service role both need
iam:PassRole, and the override role must trust CodeBuild.
Exam cues
- If the question says a build cannot read private S3 scripts, think the CodeBuild service role and bucket restrictions, because that role authorizes the read and an endpoint restriction also controls its path.
- If the question says failures or build time are increasing, think CloudWatch metrics, because they record results and duration over time.
- If the question says developers need to reproduce build commands locally, think the local agent, because it runs builds using Docker.
- If the question says react when a build changes state, think EventBridge’s
CodeBuild Build State Change, because CodeBuild sends that event directly. - If the question says shared CodeBuild projects need separate pipeline permissions, think
ServiceRoleArnOverride, because each pipeline can pass its own scoped role.
Remember
- Service role trust principal:
codebuild.amazonaws.com. FailedBuildscounts client-error and timeout failures.Durationis measured in seconds.- Local agent prerequisites include Git and Docker.
Trap: Adding permissions to a developer identity does not add them to the CodeBuild service role. Inspect the identity actually used by the build.
From the AWS docs (16)
- CodeBuild uses its service role for operations on the user behalf; grant only required permissions.
- The service role trust policy must allow codebuild.amazonaws.com to assume the role.
- A CodePipeline CodeBuild action can override the project service role with a role in the project's account; the role must trust codebuild.amazonaws.com.
- The identity creating or updating the pipeline and the CodePipeline service role both need iam:PassRole for a CodeBuild action service role override.
- The service role can be granted s3:GetObject and s3:GetObjectVersion for required S3 objects.
- CloudWatch logging permissions include logs:CreateLogGroup, logs:CreateLogStream, and logs:PutLogEvents.
- Build details are available in the console or with BatchGetBuilds.
- Build phase details include the phase type, status, and error contexts.
- CodeBuild builds can write logs to CloudWatch Logs and S3.
- CloudWatch exposes build counts, successes, failures, and build duration.
- The ProjectName CloudWatch dimension selects project metrics; omitting dimensions selects account metrics.
- FailedBuilds counts client-error or timeout failures and Duration measures build durations in seconds.
- CodeBuild sends CodeBuild Build State Change and CodeBuild Build Phase Change events directly to EventBridge.
- The CodeBuild local agent runs builds locally using Docker and requires Git and Docker.
- An S3 bucket policy can restrict requests to a particular VPC endpoint using aws:sourceVpce.
- The local build script selects a container image and artifact output directory and can select a source directory.
Flashcards
Nothing to review here right now. Pick other topics or another filter.
·
All 61 cards as a list
Where does CodeBuild find its buildspec by default, and how can a project use another file?
buildspec.ymlin the source root. Set the project buildspec or a per-buildbuildspecOverride; an S3 buildspec uses its object ARN and a bucket in the project Region. An inline project buildspec is also supported.What is the CodeBuild buildspec phase order, and what does a phase finally block do?
install,pre_build,build,post_build. A phase runs itsfinallycommands even after a command in that phase fails. Use version0.2for commands that share shell state.A CodeBuild build changes directory in one command, but the next command cannot see that change under buildspec version 0.1. What should the team change?
Use buildspec version
0.2. Version0.1starts a separate shell for each command.A CodeBuild project needs a compiler already packaged in an internal ECR image. How can the build environment use it?
Select that accessible ECR image as the build image. The image supplies the operating system, runtime, and tools; the buildspec supplies the commands.
A CodeBuild test script writes a report but returns success when its tests fail. How should the team make failed tests stop the build?
Make the test check return a failing exit status and use
on-failure: ABORTwhen the build must stop. A failed command fails its phase; merely writing a result file does not express a command failure.How can a CodeBuild post_build command tell whether the current build is failing?
Read
CODEBUILD_BUILD_SUCCEEDING:1means succeeding and0means failing.UPLOAD_ARTIFACTSis attempted even ifBUILDfails.A CodeBuild unit test command fails. How can a team stop the build while still running cleanup commands?
Use on-failure ABORT for the phase and put cleanup in finally. Finally commands run after a commands-block failure.
A CodeBuild command fails, but the next phase still runs. Which buildspec setting allows this, and where should cleanup go?
on-failure: CONTINUEallows the next phase. Put phase cleanup infinally; its commands run after a commands-block failure. A failed cleanup command also makes the phase fail.A CodeBuild test phase fails, but the team needs to upload test artifacts for analysis. Is artifact upload attempted?
Yes. CodeBuild attempts UPLOAD_ARTIFACTS even when BUILD fails.
A CodePipeline CodeBuild action fails and the team wants an automatic retry. Should it rely on the CodeBuild project's automatic build retry?
No. CodeBuild automatic build retry does not support CodePipeline. Configure an automatic CodePipeline stage retry, which makes one retry attempt.
A CodeBuild build needs a database password without placing its value in the buildspec. What should it use?
Use
env.parameter-storeorenv.secrets-manager. The role needsssm:GetParametersorsecretsmanager:GetSecretValue; reading a Secrets Manager secret under a customer managed key also needskms:Decrypt.The same CodeBuild variable is defined in the buildspec, project, and StartBuild request. Which value wins?
StartBuild first, project second, buildspec last.
A CodeBuild project stores a token as a plain environment variable. How should the team avoid exposing its value through the console and CLI?
Store it in Parameter Store or Secrets Manager and configure a reference mapping. Plain environment variables can be displayed as text.
Which secret version does a CodeBuild Secrets Manager mapping select by default, and how is a secret in another account identified?
AWSCURRENTby default. Use the secret ARN for another account. The reference format issecret-id:json-key:version-stage:version-id; choose a stage or ID, not both.A CodeBuild command prints a Base64 transformation of a Secrets Manager value. Does CodeBuild mask that transformed output?
No. Masking matches the stored value exactly. A transformation can produce visible text; store the value in the form the build needs and avoid printing secrets.
A CodeBuild project must retrieve a Parameter Store SecureString during a build. What should the team configure?
Map the parameter with env.parameter-store and grant the service role ssm:GetParameters and kms:Decrypt for its key.
A buildspec must tag an image with the exact commit that was built, even when a branch name triggered the build. Which variable fits?
CODEBUILD_RESOLVED_SOURCE_VERSION, the resolved commit ID.
A CodeBuild build needs a Secrets Manager secret encrypted with a customer managed KMS key. Which permissions are required?
Grant secretsmanager:GetSecretValue and kms:Decrypt for the key.
Which CodeBuild test and coverage formats can a buildspec report group collect?
Tests: JUnit XML, Cucumber JSON, NUnit XML, NUnit3 XML, TestNG XML, and Visual Studio TRX or TRX XML. Coverage: JaCoCo XML, Cobertura XML, Clover XML, SimpleCov JSON, and LCOV INFO.
JUNITXMLis the default report format.A team needs raw CodeBuild test results after the report expires. What should it configure?
Configure S3 export on the report group. Reports expire after
30 days; raw S3 exports do not have that CodeBuild report expiry.How does a CodeBuild buildspec publish a test report from test tool output?
Point
reports.filesat the generated result files and supply a report group name or existing group ARN. A name creates a group; each build creates a report. A project supports up to5groups.How long can a CodeBuild test report be viewed, and does S3 export extend that report lifetime?
30 daysfrom creation. S3 export preserves raw result files; it does not extend the report view lifetime.What do CodeBuild line and branch coverage measure, and which tool must generate SimpleCov JSON input?
Line coverage measures covered statements; branch coverage measures covered branches of control structures. Use
simplecov, notsimplecov-json, for SimpleCov input.A CodeBuild build should add results to an existing shared report group, but naming the group creates another group. What should the team supply?
Supply the existing report group ARN in
reports. A name creates a report group; an ARN selects an existing one.A team needs files from a CodeBuild build in a later CodePipeline action. How should it pass them?
Select files in the buildspec
artifactssection and declare the CodeBuild action output artifact. The later action consumes that output as an input.How can a CodeBuild action pass a non-secret version value to a later CodePipeline action?
List it under
env.exported-variables, give the action a namespace, and reference#{namespace.variable}later. Values stop changing at the end ofpost_build. Project-configured secrets and variables beginningAWS_cannot be exported.A CodePipeline build needs a compiled package and a separate test bundle from one CodeBuild action. How must its outputs be named?
Define both under
artifacts.secondary-artifacts. Every CodePipeline output name must match its buildspec artifact identifier.A CodeBuild project can write to S3 but cannot encrypt artifacts with a customer managed KMS key. What access should the team inspect?
Inspect access to the KMS key and its key policy for CodeBuild. S3 output permissions do not by themselves authorize use of a customer managed key.
A CodePipeline CodeBuild action receives two source artifacts. How does it find the buildspec?
Set
PrimarySourceto one input artifact. CodeBuild looks for the buildspec there and extracts each input into its own directory.A standalone CodeBuild project needs each S3 output as a ZIP under a build-specific path. Which settings matter?
Set packaging to
ZIPand namespace type toBUILD_ID. Their defaults are an uncompressed folder and no build ID.A standalone CodeBuild project needs its buildspec to generate a unique S3 artifact name. What project setting permits it?
Enable
overrideArtifactNameso the buildspec name overrides the project artifact name.A CodeBuild build uses an explicit proxy and cannot upload its artifact. Which buildspec setting should the team check?
Set
proxy.upload-artifactstoyes. It defaults tono.A CodePipeline build artifact must reach a CodeDeploy action in another account. What access is needed?
Grant the cross-account role access to the artifact bucket and customer managed KMS key, and configure its trust. An artifact cannot pass directly between two non-pipeline accounts.
A CodePipeline CodeBuild batch action needs one combined output artifact. Which options should it enable?
Enable
BatchEnabledandCombineArtifacts. The latter combines the batch builds' outputs.A CodeBuild buildspec defines only secondary artifacts. Can it omit the top-level artifacts.files sequence?
No. The top-level
artifacts.filessequence is still required.A CodeBuild BUILD phase fails. Is the artifact upload phase skipped?
No. CodeBuild still attempts
UPLOAD_ARTIFACTS.CodeBuild reports an invalid ARN while uploading an S3 artifact. What Region mismatch should the team check?
Check that the output bucket is in the same Region as the CodeBuild project.
A CodeBuild project writes S3 artifacts with default packaging, and an auditor needs the SHA-256 hash CodeBuild reports for each artifact. What must change?
Set packaging to ZIP. CodeBuild reports the SHA-256 and MD5 hashes only for ZIP-packaged artifacts; the default is an uncompressed folder.
A pipeline must verify the SHA-256 checksum CodeBuild reports for a build artifact, but the field is empty. What project setting is needed?
Artifact packaging set to ZIP; the sha256sum value is only available then.
What distinguishes CodeBuild S3 caching from local caching, and can VPC builds use local cache?
S3 cache is available across hosts. Local cache is available only on its host and is unsupported for VPC builds. Local Docker layer caching needs Linux and privileged mode.
What are the CodeBuild local cache modes?
Source caches Git metadata; Docker layer caches image layers; custom caches buildspec-listed directories. Custom mode cannot cache individual files.
A CodeBuild VPC project needs reusable dependency downloads across build hosts. Which cache fits?
Use an S3 cache. It is available across hosts; local caching is unsupported for VPC builds.
Two CodeBuild projects use an S3 cache key but do not share cached dependencies. Which settings must match?
Match
cacheNamespace, cache key, cache paths, S3 bucket, andpathPrefixif set.A CodeBuild build must reach private RDS and download internet packages. Which subnet and internet path should it use?
Use VPC configuration with private subnets and security groups, plus a NAT gateway in a public subnet. CodeBuild interfaces receive no public IP, so an internet gateway alone cannot provide internet access.
A CodeBuild VPC build needs cached dependencies and internet downloads. Which cache and network path fit?
S3 cache and NAT egress from private subnets. VPC builds cannot use local cache.
A CodeBuild VPC build only needs S3 access for dependencies in the same Region. What can provide that path without NAT?
An S3 gateway endpoint associated with the subnet route table. It has no additional charge and must be in the bucket Region.
Can a CodeCommit pull request use a CodeBuild repository webhook to start tests?
Use CodeCommit EventBridge events such as
pullRequestCreatedandpullRequestSourceBranchUpdatedwith a CodeBuild project target. CodeBuild repository webhooks support other listed providers, including GitHub, GitLab, and Bitbucket, rather than CodeCommit.A public repository triggers CodeBuild tests with a role that can deploy. How should the team reduce access from contributor code?
Separate testing and deployment projects. Give the test role no resource write permissions, filter deployment to trusted actors with
ACTOR_ACCOUNT_ID, and use an inline or S3 buildspec to prevent pull request edits to it.A GitHub repository needs CodeBuild tests when a pull request opens or receives commits. Which webhook events fit?
PULL_REQUEST_CREATEDandPULL_REQUEST_UPDATED. Filters within a group all must match; any matching group can trigger a build, subject to approval policy.A CodeBuild project must review untrusted pull requests before executing their code. What should it enable?
Pull request comment approval. An untrusted contribution is marked Failed until a trusted contributor approves the latest commit with
/codebuild_run(<latest-commit-SHA>). New projects enable the policy withALL_PULL_REQUESTSby default.What does CODEBUILD_SOURCE_VERSION contain for a GitHub pull request build triggered by a webhook?
pr/<pull-request-number>. This documented format applies to GitHub and GitHub Enterprise Server webhook pull requests.Developers want each pull request to show whether its CodeBuild build passed. Which CodeBuild setting does this?
Build status reporting, which posts the build result to the source provider.
A CodeBuild build fails when it tries to publish a Docker image to ECR. What should the team check?
Check Docker daemon availability, privileged mode for VPC Docker builds, ECR login, and the role push permissions. AWS documents the daemon as enabled by default for non-VPC builds. Docker layer caching separately requires Linux and privileged mode.
A CodeBuild build produces a Docker image locally, but no image appears in ECR. Which build step is missing?
An authenticated
docker push. In the AWS sample,pre_buildlogs in,buildbuilds and tags, andpost_buildpushes the image.Which ECR permissions does the AWS CodeBuild image publishing sample grant?
ecr:GetAuthorizationToken,ecr:BatchCheckLayerAvailability,ecr:InitiateLayerUpload,ecr:UploadLayerPart,ecr:CompleteLayerUpload, andecr:PutImage.Where should a team start when a CodeBuild build fails?
Inspect build phase details and the configured CloudWatch Logs or S3 logs. Phase status and error context identify the failing operation; compare it with the service role permissions and network path.
A CodeBuild build needs deployment scripts from private S3 without embedded access keys. What should the team configure?
Grant its service role
s3:GetObjectands3:GetObjectVersionfor the required objects. If the bucket restricts access withaws:sourceVpce, the build must use the permitted VPC endpoint.A team wants to reproduce a CodeBuild build on a developer machine to diagnose build commands. Which tool fits?
The CodeBuild local agent. Install Git and Docker, select the build image, and run the local build script with source and output locations.
A team needs to compare CodeBuild failures and build duration for one project over time. What should it inspect?
CloudWatch metrics with the
ProjectNamedimension, includingFailedBuildsandDuration. Omitting dimensions selects account metrics.Which CodeBuild event can EventBridge match to react to a build result?
CodeBuild Build State Change. CodeBuild also sendsCodeBuild Build Phase Changeevents for phase transitions.A shared CodeBuild project needs a separate least-privilege role for each CodePipeline pipeline. How can the pipeline use an override role?
Set
ServiceRoleArnOverrideon the CodeBuild action. The role must be in the project account and trust CodeBuild; both the pipeline editor and pipeline service role neediam:PassRole.