Cloud / AWS CodeBuild Interview questions
Last updated
1. What is AWS CodeBuild?
AWS CodeBuild is a fully managed continuous integration service that compiles source code, runs tests, and produces deployable artifacts. You never provision or patch build servers. CodeBuild starts a fresh, isolated container for each build and discards it when the build ends.
Builds scale out automatically, so several can run at the same time instead of waiting for a free agent. You pay only for the build minutes you consume.
Instructions come from a buildspec file. Source can come from CodeCommit, GitHub, Bitbucket, GitLab or S3, and output usually goes to S3 or a container registry such as ECR. It is most often used as the build and test stage of an AWS CodePipeline pipeline.
Take quiz
In a fresh, isolated container that is discarded afterward
On the developer's laptop through a local agent
On a long-running shared server that you patch yourself
Build minutes consumed, priced by compute type
The number of repositories connected
A flat monthly fee per project
The number of buildspec files stored
2. What are the key features of AWS CodeBuild?
CodeBuild removes the need to run your own build fleet while still giving you control over the build environment.
- Fully managed: no servers to patch, and builds scale automatically with demand.
- Pay per use: billed by build minute and compute type.
- Flexible environments: AWS curated images or your own Docker image, with several CPU/memory sizes.
- buildspec-driven: build steps live in YAML alongside your code.
- Integrations: CodePipeline, IAM, KMS, VPC, CloudWatch, EventBridge and Secrets Manager.
- Reports and caching: test and code coverage reports, S3 and local caches.
- Batch builds and local debugging tools for larger or trickier pipelines.
It builds and tests only. Rolling out the result to servers is the job of a service such as CodeDeploy.
Take quiz
Rolling deployments to an EC2 fleet
Publishing test reports
Producing build artifacts
Running unit tests
Report groups
Build badges
VPC configuration on the project
Buildspec version 0.2
3. What is a build project in AWS CodeBuild?
A build project is the saved configuration that tells CodeBuild how to run builds. A build is a single execution of that project.
A project defines the source location, the environment (image, compute type, privileged mode, environment variables), the service role, where the buildspec comes from, artifact and cache settings, log destinations, timeouts, and optional VPC settings.
Most of these can be overridden for one run, for example a different branch or extra environment variables passed to StartBuild, without changing the project itself.
Take quiz
The buildspec.yml file itself
One execution of a build project
The saved definition of source and environment
Compute type, image and service role
Individual log lines from the last run
The exit code of the most recent build
The commit that triggered a build
4. What is a buildspec file in CodeBuild?
A buildspec is a YAML file that lists the commands and settings CodeBuild uses to run a build. It usually lives in the repository root, so build logic is versioned with the code.
Top-level keys include version, env, phases, reports, artifacts, cache and batch. Only version and phases are needed for a simple build.
version: 0.2 phases: install: runtime-versions: nodejs: 20 commands: - npm ci build: commands: - npm test - npm run build artifacts: files: - '**/*' base-directory: dist
Take quiz
Dockerfile syntax
XML
YAML
Groovy DSL
stages
jobs
steps
phases
5. What are the phases of a buildspec file?
A buildspec has four command phases that run in a fixed order: install, pre_build, build and post_build. Each holds a list of shell commands under commands.
| Phase | Typical use |
| install | Install runtimes and tools, run npm ci or pip install |
| pre_build | Log in to ECR, fetch config, set variables |
| build | Compile, run tests, build the Docker image |
| post_build | Push images, package output, check CODEBUILD_BUILD_SUCCEEDING |
All four are optional, but the order is not configurable. Extra steps such as source download and artifact upload are handled by CodeBuild between and after them.
Take quiz
pre_build
artifacts
post_build
install
cache
pre_build
post_build
install
6. What is the default name and location of the buildspec file?
By default CodeBuild looks for a file named buildspec.yml in the root of the primary source.
You can change that in three ways: point the project at another file such as ci/buildspec-prod.yml, paste the buildspec inline in the project definition, or pass buildspecOverride when starting a build. An override on StartBuild wins over the project setting, which wins over the default file.
Inline buildspecs are handy for quick jobs, but keeping the file in the repo makes changes reviewable.
Take quiz
Jenkinsfile at the source root
buildspec.yml at the source root
codebuild.yml in a .aws folder
build.json at the source root
Define it inline in the project
Attach it to a report group
Rename it to buildspec.txt
Store it in a build badge
7. Which source providers does CodeBuild support?
CodeBuild can pull code from AWS CodeCommit, Amazon S3, GitHub, GitHub Enterprise Server, Bitbucket and GitLab (including self-managed GitLab). Inside a pipeline, the source type is CodePipeline, meaning the pipeline hands over the code. A project can also have no source when the buildspec does all the work.
Webhooks for automatic builds are available for GitHub, GitHub Enterprise, Bitbucket and GitLab. S3 has no push trigger, and CodeCommit builds are usually started through EventBridge rules.
Take quiz
GitLab
GitHub
Bitbucket
Amazon S3
CODEPIPELINE
S3 with versioning
NO_SOURCE
BITBUCKET
8. What are the compute types available in CodeBuild?
Compute type controls vCPUs and memory of the build container. For Linux on x86 the general-purpose sizes are:
| Compute type | vCPUs | Memory |
| BUILD_GENERAL1_SMALL | 2 | 3 GB |
| BUILD_GENERAL1_MEDIUM | 4 | 7 GB |
| BUILD_GENERAL1_LARGE | 8 | 15 GB |
Larger sizes such as XLARGE and 2XLARGE exist for heavy builds. The environment type then picks the platform: Linux, ARM, Linux GPU, Windows Server, or Lambda-based compute. Not every combination is offered in every Region.
Bigger machines cost more per minute, but a faster build can end up cheaper overall.
Take quiz
2
4
8
A smaller cache
BUILD_GENERAL1_SMALL
BUILD_GENERAL1_LARGE or larger
A Lambda compute type
9. What are curated build environment images in CodeBuild?
Curated images are Docker images maintained by AWS and preloaded with common tooling: Git, the AWS CLI, Docker, and runtimes such as Java, Node.js, Python, Go, .NET, Ruby and PHP. They come in Ubuntu-based (for example aws/codebuild/standard:7.0) and Amazon Linux flavours.
Only curated images support the runtime-versions setting in the buildspec.
If you need something else, bring a custom image from ECR, Docker Hub or another registry. Baking your tools into a custom image saves install time on every build.
Take quiz
AWS curated images
Only Windows images
Any image pulled from Docker Hub
ECR or Docker Hub
Only in CodeCommit
Only in an S3 bucket
Only in Parameter Store
10. What are the artifact options in CodeBuild?
A project's artifact type is one of three values:
- NO_ARTIFACTS: nothing is uploaded, for example when the build only pushes a Docker image.
- S3: files are uploaded to a bucket, with optional path, name, ZIP packaging and a build-ID namespace.
- CODEPIPELINE: CodePipeline stores the output and passes it to the next stage.
Which files are collected is defined in the buildspec artifacts section. Secondary artifacts let one build produce several outputs.
With S3 you can turn on ZIP packaging and a BUILD_ID namespace, so each build writes to its own folder instead of overwriting the previous output.
Take quiz
NO_ARTIFACTS
CODEPIPELINE
LOCAL
ECR
NO_ARTIFACTS
An ECR artifact type
S3 with ZIP packaging
CODEPIPELINE always
11. What are the types of environment variables in CodeBuild?
Each environment variable has a type:
- PLAINTEXT: stored as-is and visible in the console and API. Use it for non-sensitive values like a stage name.
- PARAMETER_STORE: the value is the name of a Systems Manager parameter, resolved when the build runs.
- SECRETS_MANAGER: the value references a Secrets Manager secret, resolved at build time.
Variables can be set on the project, overridden per StartBuild, or declared in the buildspec env section. Never put passwords in PLAINTEXT variables.
Take quiz
PLAINTEXT
A build badge URL
A committed .env file
SECRETS_MANAGER
StartBuild overrides or the buildspec env section
Cache paths
Report groups
The artifacts section
12. What are some built-in environment variables in CodeBuild?
CodeBuild injects variables into every build, all prefixed with CODEBUILD_. That prefix is reserved, so you cannot define your own variables with it.
| Variable | Meaning |
| CODEBUILD_BUILD_ID | Unique ID of this build |
| CODEBUILD_BUILD_NUMBER | Sequence number within the project |
| CODEBUILD_SRC_DIR | Directory where the source was placed |
| CODEBUILD_RESOLVED_SOURCE_VERSION | Commit ID (or version) actually built |
| CODEBUILD_INITIATOR | Who or what started the build |
| CODEBUILD_BUILD_SUCCEEDING | 1 while the build is succeeding, 0 after a failure |
AWS_REGION and AWS_DEFAULT_REGION are also set for you.
A common pattern is tagging an image or naming an artifact with CODEBUILD_RESOLVED_SOURCE_VERSION or CODEBUILD_BUILD_NUMBER, so every output can be traced back to the exact build.
Take quiz
CODEBUILD_RESOLVED_SOURCE_VERSION
CODEBUILD_INITIATOR
CODEBUILD_SRC_DIR
CODEBUILD_BUILD_ID
The build has already failed at some point
The build was triggered manually
The build has not started yet
13. How do you start a build in CodeBuild?
There are several entry points: the console's Start build button, the CLI or SDKs, repository webhooks, a CodePipeline build action, and EventBridge rules (including scheduled ones).
aws codebuild start-build \ --project-name my-app \ --source-version feature/login \ --environment-variables-override name=STAGE,value=dev,type=PLAINTEXT
The overrides apply only to that build. For nightly runs, create an EventBridge schedule rule that targets the project.
A build started from the CLI or console uses the project's settings by default. Webhooks and pipelines start builds automatically, which is what most teams rely on day to day. Each run gets its own build ID, which you can pass to batch-get-builds to check its status and logs.
Take quiz
aws codebuild start-build
aws codebuild invoke-project
aws codebuild create-build
aws codebuild run-build
A build badge setting
A cron key in the buildspec
A schedule on the report group
An EventBridge scheduled rule targeting the project
14. What is the CodeBuild service role?
The service role is the IAM role CodeBuild assumes to run your build. Its trust policy names codebuild.amazonaws.com as the principal.
Every AWS call made inside the build, whether by CodeBuild itself or by the AWS CLI in your commands, uses this role's credentials, not those of the person who started the build. It typically needs permissions for CloudWatch Logs, the S3 buckets used for source, artifacts and cache, ECR, any secrets or parameters read, KMS keys, and network interfaces if the project uses a VPC.
Take quiz
codepipeline.amazonaws.com
codebuild.amazonaws.com
lambda.amazonaws.com
ec2.amazonaws.com
The account root user
The project's service role
The GitHub user who pushed the code
The user who started the build
15. Where does CodeBuild store build logs?
Logs can go to CloudWatch Logs, Amazon S3, or both. By default CodeBuild writes to a log group named /aws/codebuild/<project-name>, with a stream per build, and you can watch output live in the console.
The service role needs permission to write to whichever destination you choose. CloudWatch log groups never expire by default, so set a retention period to control cost.
Logs are also useful outside the console. You can search them with CloudWatch Logs Insights, or create a metric filter that raises an alarm on a specific error string.
Take quiz
/aws/lambda/
/aws/codebuild/
/codebuild/logs/
/aws/codepipeline/
CloudTrail and Config
EFS and DynamoDB
X-Ray and Kinesis
CloudWatch Logs and S3
16. How is AWS CodeBuild priced?
CodeBuild is pay-as-you-go. You are billed per minute of build duration, and the rate depends on the compute type and platform. Bigger or GPU machines cost more per minute. A small monthly free tier applies to the smallest Linux compute type.
Reserved capacity fleets are different: you pay for the reserved instances while they exist, whether or not builds are running.
Related services bill separately, for example S3 storage, CloudWatch Logs, ECR, and NAT gateway charges for builds inside a VPC.
Take quiz
The number of projects created
Build duration multiplied by compute type rate
The size of the buildspec file
The number of commits pushed
Per-webhook fees
NAT gateway usage
A YAML parsing fee
A per-project license
17. What are the default build and queue timeouts in CodeBuild?
The build timeout defaults to 60 minutes and can be set from 5 minutes up to 36 hours. A build that exceeds it is stopped with a timed-out status.
The queue timeout is how long a build may wait for capacity, for example when the account's concurrent build limit is reached. It defaults to 8 hours and ranges from 5 minutes to 8 hours.
Set both deliberately: a hung test suite should not burn build minutes for an hour.
Take quiz
8 hours
15 minutes
24 hours
60 minutes
While Docker layers are pulled
During artifact upload
While a build waits for available capacity
After the build finishes
18. What are test reports in CodeBuild?
CodeBuild can collect test reports and code coverage reports produced by your tools and show them in the console, with pass/fail counts and trends over time.
Reports are declared in the buildspec reports section. Each entry becomes a report group.
reports: unit-tests: files: - 'target/surefire-reports/*.xml' file-format: JUNITXML
Supported test formats include JUnit XML, NUnit, Cucumber JSON, TestNG XML and Visual Studio TRX. Coverage formats include JaCoCo, Clover, Cobertura and SimpleCov. Raw results can also be exported to S3.
Take quiz
JUNITJSON
JUNITXML
XUNITCSV
SUREFIRETXT
Report group
Batch group
Log group
Artifact group
19. What is the runtime-versions setting in a buildspec?
runtime-versions tells a curated image which language runtimes to install or switch to during the install phase, so you don't script the setup yourself.
version: 0.2 phases: install: runtime-versions: java: corretto17 python: 3.12 commands: - mvn -v
It needs buildspec version 0.2 and a curated image. Custom images ignore it, so they must already contain the runtime you want.
You can list several runtimes at once, for example Java and Node.js in a full-stack build. Some images also accept latest, but pin exact versions when you need reproducible builds.
Take quiz
1.0
0.1
0.2
0.0
Under artifacts
Under cache
Under phases.install
Under env
20. What are build badges in CodeBuild?
A build badge is a URL that returns an image showing the pass/fail status of the latest build for a branch. Enable it in the project settings and paste the URL into your README as a Markdown image.
The badge URL is publicly accessible, even if the repository is private, but it only exposes the build status. Badges are not available for projects that use CodePipeline as the source.
The badge reflects one branch, so choose the branch that represents your release line, such as main, so the image shows what readers actually care about.
Take quiz
Code coverage percentage
Number of contributors
Monthly build cost
Pass/fail status of the latest build
In the cache section
In the IAM trust policy
In the repository README
In the VPC configuration
21. What is the difference between buildspec version 0.1 and 0.2?
The key difference is how commands share a shell. In 0.1, every command runs in its own shell instance, so a cd or export in one command is gone by the next. In 0.2, all commands run in the same shell instance, so directory changes and exported variables carry across commands and phases.
| Behaviour | Version 0.1 | Version 0.2 |
| Shell per command | New shell each time | Same shell throughout |
| cd / export persist | No | Yes |
| runtime-versions | Not supported | Supported |
| Recommended | Legacy only | Yes, for all new projects |
With 0.1 you had to chain commands with && or wrap them in scripts. Use 0.2 unless you are maintaining an old project.
Take quiz
It is reset before each command
It persists for later commands
It is ignored by CodeBuild
0.2
Both 0.1 and 0.2
Neither
0.1
22. Explain the lifecycle of a CodeBuild build?
Every build moves through a set of phases you can see in the console under Phase details. CodeBuild first accepts and queues the request, then provisions the container by pulling the image and applying VPC and compute settings.
It then downloads the source and runs your buildspec phases (install, pre_build, build, post_build). Afterwards it uploads artifacts and finalizes the build, which includes shutting down the container and writing logs and reports.
flowchart LR A[SUBMITTED] --> B[QUEUED] B --> C[PROVISIONING] C --> D[DOWNLOAD_SOURCE] D --> E[INSTALL] E --> F[PRE_BUILD] F --> G[BUILD] G --> H[POST_BUILD] H --> I[UPLOAD_ARTIFACTS] I --> J[FINALIZING] J --> K[COMPLETED]
Each phase reports its own status and duration. When a build fails, the phase list shows exactly where, which is the first place to look while troubleshooting.
Take quiz
DOWNLOAD_SOURCE
INSTALL
PROVISIONING
FINALIZING
Artifacts are copied to S3
A notification is sent through SNS
Unit tests run
The build container is created and the image pulled
23. How does CodeBuild integrate with CodePipeline?
In a pipeline, CodeBuild runs as an action in a Build or Test stage. The Source stage stores the code as an artifact in the pipeline's artifact bucket, and the CodeBuild action receives it as its input artifact.
Inside the project, source and artifact types are set to CODEPIPELINE. Whatever the buildspec artifacts section collects becomes the action's output artifact, which later stages such as CodeDeploy or CloudFormation consume.
The pipeline's role needs codebuild:StartBuild and codebuild:BatchGetBuilds, and the CodeBuild service role needs access to the pipeline's artifact bucket and KMS key. Variables can be passed forward using exported-variables.
Take quiz
CODEPIPELINE
S3 with ZIP
GITHUB
NO_ARTIFACTS
The CloudWatch log stream
The container image layers
The build badge
The output artifact defined in the buildspec
24. How do you cache dependencies in CodeBuild?
Caching is configured in two places. On the project you choose the cache type: S3 or local. In the buildspec you list the folders to keep under cache.paths.
cache: paths: - '/root/.m2/**/*' - '/root/.npm/**/*'
With an S3 cache, CodeBuild restores those paths at the start and uploads them at the end. With local cache you pick modes: LOCAL_SOURCE_CACHE, LOCAL_DOCKER_LAYER_CACHE or LOCAL_CUSTOM_CACHE (the last uses your cache.paths).
Cache only what is expensive to rebuild, such as dependency folders, not build output. Stale compiled output can hide errors, and an oversized S3 cache can take longer to download than the dependencies take to fetch fresh.
Take quiz
phases.cache
cache.paths
artifacts.cache
env.paths
/var/log/**/*
/tmp/build-output
/etc/ssh/**/*
/root/.m2/**/*
25. What is the difference between S3 cache and local cache?
S3 cache stores the cache in a bucket, so it is durable and shared across build hosts. Local cache stays on the build host, so it is faster but best-effort: it only helps when a later build lands on the same host.
| Aspect | S3 cache | Local cache |
| Storage | S3 bucket | Build host |
| Persistence | Durable | Best effort |
| Speed | Download/upload each build | No transfer needed |
| Docker layer cache | Not supported | Supported |
| Extra cost | S3 storage | None |
Use S3 cache for dependencies when you need predictable hits. Use local cache for Docker layers and large source trees where speed matters more than guaranteed reuse.
Take quiz
Local cache
Both equally
Neither
S3 cache
It needs a customer managed KMS key
It only works for Windows builds
The next build may run on a different host
It expires after one build
26. Why does a Docker build need privileged mode in CodeBuild?
Build containers run unprivileged by default, and the Docker daemon needs elevated capabilities to start. Enabling privileged mode lets the container run dockerd so commands like docker build and docker push work.
Without it you will see Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Curated images start the daemon for you, while a custom image must start it in the buildspec.
Privileged mode widens what the build container can do, so use it only for trusted source code, for example not for pull requests from unknown forks.
Docker builds also run slowly on small compute, so combine privileged mode with a larger compute type and local Docker layer caching.
Take quiz
AccessDenied on s3:GetObject
Build timed out in QUEUED
YAML_FILE_ERROR
Cannot connect to the Docker daemon
Bypassing VPC settings
Skipping IAM checks
Disabling CloudWatch logging
Running the Docker daemon inside the build container
27. How do you build and push a Docker image to ECR with CodeBuild?
Enable privileged mode, give the service role ECR push permissions, and set variables such as ACCOUNT_ID and REPO_URI on the project.
version: 0.2 phases: pre_build: commands: - aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com - IMAGE_TAG=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c1-7) build: commands: - docker build -t $REPO_URI:$IMAGE_TAG . post_build: commands: - docker push $REPO_URI:$IMAGE_TAG
The role needs ecr:GetAuthorizationToken plus the layer upload actions (InitiateLayerUpload, UploadLayerPart, CompleteLayerUpload, PutImage) on the target repository. Tagging with the commit ID keeps images traceable.
Take quiz
docker ecr auth
aws ecr login-docker
aws codebuild get-ecr-token
aws ecr get-login-password
ecr:DescribeImages
codebuild:StartBuild
ecr:GetAuthorizationToken
s3:GetObject
28. How do you securely pass secrets to a CodeBuild build?
Reference secrets instead of embedding them. The buildspec env section can pull values from Parameter Store and Secrets Manager when the build starts.
env: parameter-store: DB_HOST: /myapp/prod/db-host secrets-manager: DB_PASSWORD: prod/myapp/db:password
The secret reference format is secret-id:json-key:version-stage:version-id, where the trailing parts are optional. The service role needs ssm:GetParameters or secretsmanager:GetSecretValue, and kms:Decrypt if a customer managed key protects the value.
Avoid PLAINTEXT variables for secrets, never commit them, and don't echo them into logs or artifacts.
Use Parameter Store for plain configuration and Secrets Manager for credentials that need rotation. After a rotation, the next build automatically picks up the new value.
Take quiz
env.variables
env.secrets-manager
env.kms-secrets
phases.secrets
kms:CreateKey
s3:PutObject
kms:Decrypt
iam:CreateRole
29. How do webhook filter groups work in CodeBuild?
A webhook starts builds when your repository sends an event. A filter group is a set of conditions that must all match (AND). If you define several groups, the build starts when any one group matches (OR).
Filter types include EVENT (for example PUSH, PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_MERGED), HEAD_REF, BASE_REF, FILE_PATH, COMMIT_MESSAGE and ACTOR_ACCOUNT_ID. Patterns are regular expressions, and a filter can be flipped to exclude matches.
Example: one group for PUSH with HEAD_REF ^refs/heads/main$, and another for pull requests whose BASE_REF is main and whose FILE_PATH touches ^src/.
Test filter groups against a throwaway repository first. An over-broad pattern can start a build on every push and quietly raise costs.
Take quiz
AND inside a group, OR between groups
OR inside a group only
XOR across groups
AND between all groups
ACTOR_ACCOUNT_ID with no other filter
EVENT = PULL_REQUEST_CREATED only
COMMIT_MESSAGE = main with no EVENT
EVENT = PUSH and HEAD_REF = ^refs/heads/main$
30. How do you run CodeBuild inside a VPC?
In the project's VPC settings, choose the VPC, one or more subnets and security groups. CodeBuild then creates elastic network interfaces in those subnets so the build can reach private resources such as RDS, an internal package repository or a private API.
Use private subnets with a route to a NAT gateway if the build also needs the internet. To reduce NAT traffic, add VPC endpoints for S3, ECR and CloudWatch Logs.
The service role must be allowed to manage network interfaces (ec2:CreateNetworkInterface, DescribeNetworkInterfaces, DeleteNetworkInterface, CreateNetworkInterfacePermission and a few Describe calls). Security groups must allow outbound traffic to the targets.
Take quiz
A subnet with no routes
A public subnet with an internet gateway only
The default subnet without a security group
A private subnet routed through a NAT gateway
To enable privileged mode
To raise the build timeout
To turn on webhooks
To reach them without sending traffic through NAT
31. Why does a CodeBuild VPC build fail to reach the internet?
The usual cause is that CodeBuild network interfaces never get a public IP. A build placed in a public subnet still can't reach the internet, even with an internet gateway attached. It needs a private subnet with a default route to a NAT gateway.
Work through this checklist when downloads time out:
- Confirm the subnet is private and its route table sends
0.0.0.0/0to a NAT gateway. - Check the NAT gateway itself sits in a public subnet with an internet gateway route.
- Verify security group egress and network ACL rules allow the traffic and return ports.
- If the subnets have no internet at all, add VPC endpoints for S3, ECR and CloudWatch Logs.
- Look at the failing phase: DOWNLOAD_SOURCE or PROVISIONING points to connectivity, INSTALL to package repositories.
Take quiz
Build interfaces have no public IP, so a NAT route is needed
Privileged mode is off
Buildspec version is 0.1
Caching is disabled
The build badge
The report group
The subnet route table and security group egress
The artifact packaging type
32. How do batch builds work in CodeBuild?
A batch build runs several builds from one request, for example the same tests on multiple runtimes. You define it in a batch section of the buildspec and start it with start-build-batch.
batch: fast-fail: true build-list: - identifier: node18 env: image: aws/codebuild/standard:7.0 - identifier: node20 env: image: aws/codebuild/standard:7.0
Batches can use build-list, build-matrix, build-graph or build-fanout. Options such as fast-fail stop the batch on the first failure, and artifacts or reports from the individual builds can be combined. A batch service role and batch timeout are set on the project.
Batch builds are billed as the sum of the individual builds, so a wide matrix multiplies cost as well as coverage.
Take quiz
aws codebuild start-batch
aws codebuild run-batch-build
aws codebuild batch-run
aws codebuild start-build-batch
batch
matrix
strategy
parallel
33. What is the difference between build-list, build-matrix, and build-graph?
They are batch strategies that differ in how the child builds are described and ordered.
| Strategy | How it works | Use it for |
| build-list | You list each build explicitly; all run in parallel | A few hand-picked variants |
| build-matrix | You define dimensions and CodeBuild creates every combination | Runtimes x architectures |
| build-graph | Builds declare depend-on and run as a dependency graph |
Build, then test, then package |
| build-fanout | One build is split into parallel shards | Speeding up a big test suite |
Matrix saves typing when combinations multiply, and graph is the choice when one build needs another's output.
Whichever you pick, give each child build a clear identifier. It becomes part of the build's name in the console and makes failures easy to find.
Take quiz
build-fanout
build-list
build-graph
build-matrix
build-fanout
build-list
build-matrix
build-graph
34. How do you debug a running build with Session Manager?
Add codebuild-breakpoint to a buildspec command list where you want the build to pause. Start the build with session connection enabled (a console option, or --debug-session-enabled in the CLI).
When execution reaches the breakpoint, the build pauses and the console shows a Session Manager link. Open it to get a shell inside the live container, inspect files and environment variables, and try commands. Run codebuild-resume to let the build continue.
The service role needs the ssmmessages permissions for the session channel. The build keeps running, and being billed, while it is paused, so don't leave sessions idle.
Take quiz
exit 0
codebuild-resume
ssm-resume
codebuild-continue
AWS Cloud9
AWS Systems Manager Session Manager
AWS CloudShell
EC2 Instance Connect
35. How can you run CodeBuild builds locally?
AWS provides a CodeBuild local agent as a Docker image, plus a helper script codebuild_build.sh, so you can run a buildspec on your own machine with Docker.
./codebuild_build.sh -i aws/codebuild/standard:7.0 -s . -a ./artifacts -c
Here -i selects the image, -s the source folder, -a the artifact output and -c copies your local AWS credentials. It is a good way to catch YAML mistakes and failing commands before pushing.
It is not a perfect copy: the real service role, VPC networking and webhook triggers can't be reproduced locally.
Take quiz
The SAM CLI
A Jenkins agent
Only the AWS console
Docker with the CodeBuild local agent image
Shell command failures
Runtime installation steps
Buildspec YAML syntax
VPC connectivity and service role permissions
36. How do you pass variables from CodeBuild to CodePipeline?
Declare the variable under env.exported-variables in the buildspec and set it during the build. CodeBuild returns it to the pipeline, which makes it available to later actions.
version: 0.2 env: exported-variables: - IMAGE_TAG phases: build: commands: - export IMAGE_TAG=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c1-7)
In the pipeline, give the CodeBuild action a namespace, for example BuildVariables. A later action then reads the value as #{BuildVariables.IMAGE_TAG}.
Exported values show up in the build details, so never export secrets.
This is the cleanest way to hand a computed value, such as an image tag or version number, to a deploy action without writing it to a file and parsing it later.
Take quiz
$(pipeline.variable)
#{Namespace.VARIABLE_NAME}
${CODEBUILD_VARIABLE}
{{ variable }}
phases.post_build.export
cache.exports
env.exported-variables
artifacts.variables
37. How do you troubleshoot a failed CodeBuild build?
Start with Phase details to see which phase failed, then read the build log in CloudWatch for the actual error. The phase narrows the cause quickly:
| Failing phase / error | Likely cause |
| YAML_FILE_ERROR | Malformed buildspec, often bad indentation |
| DOWNLOAD_SOURCE | Source credentials, webhook connection or branch name |
| PROVISIONING | Image pull failure, Docker Hub rate limit, VPC or role problem |
| INSTALL / BUILD | A command returned a non-zero exit code, or a missing tool |
| UPLOAD_ARTIFACTS | The files pattern matched nothing, or S3/KMS access is denied |
| AccessDenied in logs | The service role is missing a permission |
If the log isn't enough, reproduce the build with the local agent or pause it with codebuild-breakpoint and inspect the live container.
Take quiz
The buildspec is malformed
A NAT gateway is missing
The cache bucket is full
Privileged mode is on
The build badge
The report group page
Cost Explorer
The Phase details tab of the build
38. How can you optimize CodeBuild build times?
Look at the phase durations first, then attack the slowest one.
- Cache dependencies (Maven, npm, pip) with S3 cache, and Docker layers with local cache.
- Bake tools into a custom image so the install phase doesn't download them on every run.
- Right-size the compute type. A larger instance can finish so much sooner that it costs less.
- Parallelize with batch builds or build-fanout to split a long test suite.
- Use a shallow clone (git clone depth) so large histories aren't downloaded.
- Use reserved capacity to skip provisioning for frequent builds, and VPC endpoints to cut network detours.
Measure after each change so you know which one actually helped.
Take quiz
Enable a build badge
Increase the build timeout
Disable CloudWatch logs
Cache the npm folders using cache.paths
It adds vCPUs automatically
It removes the need for a buildspec
The install phase no longer downloads them each build
It bypasses IAM checks
39. When should you use reserved capacity fleets in CodeBuild?
A reserved capacity fleet is a pool of pre-provisioned instances dedicated to your account. Builds skip the provisioning phase, and because instances are reused, caches and pulled images can survive between builds.
Consider it when you run builds frequently and need fast starts, when you want predictable capacity, or when you build for platforms like macOS (for example iOS apps). You choose the compute type, base capacity, and what happens on overflow: queue the build or fall back to on-demand.
The trade-off is cost: you pay for reserved instances even while idle. For sporadic builds, standard on-demand capacity is cheaper.
Take quiz
You pay for reserved instances even when idle
Caches can never persist
VPC use is impossible
IAM roles are not supported
A rare monthly Linux script
A tiny Lambda packaging job
A one-off experiment
Building iOS apps on macOS
40. When would you choose Lambda compute in CodeBuild?
Lambda compute runs a build on Lambda-style infrastructure instead of a full container host. It starts much faster, which suits short, lightweight jobs such as unit tests for a small service or packaging a function.
The limits matter. Lambda compute doesn't support Docker image builds or tasks that need privileged mode or root-level tooling, and its maximum build duration is far below the normal 36 hours. Check the current documentation for the exact restrictions in your Region.
Choose it for quick feedback on small builds, and stay on standard compute for Docker builds, big compiles and long test runs.
Take quiz
Building a Docker image with dockerd
A multi-hour ML training job
Building an iOS app
Fast unit tests for a small service
Unlimited build duration
GPU access by default
Privileged Docker support
Very fast startup for short builds
41. What is the difference between CodeBuild and Jenkins?
CodeBuild is a managed build runner. Jenkins is a self-hosted automation server you install, scale and maintain yourself.
| Aspect | CodeBuild | Jenkins |
| Infrastructure | Fully managed | You run controller and agents |
| Scaling | Automatic, concurrent builds | Manual or plugin-driven agents |
| Pricing | Per build minute | Infrastructure plus admin time |
| Configuration | buildspec YAML | Jenkinsfile (Groovy) |
| Orchestration | Needs CodePipeline for multi-stage flows | Built-in pipelines |
| Ecosystem | Native AWS integrations | Very large plugin catalog |
| State | Ephemeral containers | Persistent workspaces possible |
Jenkins wins on flexibility and plugins. CodeBuild wins when you want no servers and tight IAM integration.
For teams already on AWS, a common middle path is keeping Jenkins as the orchestrator and letting CodeBuild run heavy jobs as elastic build capacity.
Take quiz
It requires you to manage agents
It is fully managed and scales automatically
It needs a controller server you patch
It is configured with a Groovy DSL
A very large plugin ecosystem with built-in orchestration
No infrastructure to maintain
Native IAM service roles
Per-minute pricing with no servers
42. What is the difference between CodeBuild and CodePipeline?
CodeBuild executes build and test commands in a container. CodePipeline orchestrates the workflow: it detects source changes and moves artifacts through stages such as Source, Build, Test and Deploy.
| Aspect | CodeBuild | CodePipeline |
| Role | Runs the commands | Coordinates the stages |
| Configured with | buildspec and project settings | Stages and actions |
| Standalone use | Yes, via webhooks, CLI, EventBridge | Needs actions like CodeBuild to do real work |
| Typical output | Artifacts, images, reports | A delivery flow with approvals |
They are usually combined: the pipeline calls CodeBuild as one of its actions.
Because of this split, changing pipeline stages doesn't touch the buildspec, and changing build steps doesn't require editing the pipeline.
Take quiz
AWS CodePipeline
Amazon ECR
AWS CodeArtifact
AWS CodeBuild
Yes, using webhooks, the CLI or EventBridge
Only when the source is CodeCommit
No, it only runs inside a pipeline
43. How do CodeBuild-hosted GitHub Actions runners work?
CodeBuild can act as an ephemeral runner for GitHub Actions workflows. You connect the project to GitHub and create a webhook with the WORKFLOW_JOB_QUEUED event. When a workflow job is queued, CodeBuild starts a runner for it.
In the workflow, point the job at the project using a special label:
jobs: test: runs-on: codebuild-my-project-${{ github.run_id }}-${{ github.run_attempt }} steps: - uses: actions/checkout@v4 - run: npm test
You keep the GitHub Actions workflow syntax but run on AWS compute with IAM roles, VPC access and the usual CodeBuild compute options, with no runner servers to manage.
Take quiz
runs-on: self-hosted-aws
uses: aws/codebuild@v1
runs-on: aws-codebuild
runs-on: codebuild-<project>-${{ github.run_id }}-${{ github.run_attempt }}
PULL_REQUEST_MERGED
WORKFLOW_JOB_QUEUED
RELEASED
PUSH only
44. How do you monitor CodeBuild builds?
Several AWS services cover different angles:
- CloudWatch metrics in the
AWS/CodeBuildnamespace, such asBuilds,SucceededBuilds,FailedBuildsandDuration, with alarms on failure counts. - CloudWatch Logs for the full command output of each build.
- EventBridge events named CodeBuild Build State Change and CodeBuild Build Phase Change for automation.
- CloudTrail for API activity, for example who started or modified a project.
A common setup is an alarm on FailedBuilds plus an EventBridge rule that posts failures to a chat channel.
Alarm on duration as well as failures. A sudden jump in Duration often signals a cache miss or a slow dependency source before builds actually start failing.
Take quiz
Custom/CodeBuild
AWS/CodePipeline
AWS/Build
AWS/CodeBuild
CodeBuild Job Finished
CodeBuild Build Complete
CodeBuild Build State Change
Build Status Update
45. How do you send notifications for CodeBuild build results?
The most flexible method is an EventBridge rule matching build state changes, sent to an SNS topic, Lambda function or AWS Chatbot for Slack and Teams.
{ "source": ["aws.codebuild"], "detail-type": ["CodeBuild Build State Change"], "detail": { "build-status": ["FAILED"], "project-name": ["my-app"] } }
You can also create a notification rule from the console (Developer Tools notifications) that targets SNS or Chatbot without writing a pattern, and add pipeline-level notifications if CodeBuild runs inside CodePipeline.
Keep alerts narrow. Filtering on FAILED for a single project avoids flooding a channel, and you can add a second rule for STOPPED if cancelled builds matter to you.
Take quiz
detail.state-name
detail.exit-code
detail.build-status
detail.result
Amazon Inspector
AWS Config
AWS CodeArtifact
AWS Chatbot
46. How does CodeBuild encrypt artifacts, cache, and logs?
Build artifacts and S3 cache are encrypted at rest with KMS. If you set no key on the project, CodeBuild uses the AWS managed key for S3 (aws/s3). Pick a customer managed key if you need control over key policy and rotation.
With a customer managed key, both the service role and the key policy must allow it to use the key (kms:Decrypt, kms:GenerateDataKey and related actions). If a pipeline is involved, its artifact bucket key must also be accessible.
Logs are protected separately: encrypt the CloudWatch log group with its own KMS key, and use bucket encryption for S3 logs. Data in transit uses TLS, and secrets should come from Secrets Manager or Parameter Store.
Take quiz
The AWS managed key for S3 (aws/s3)
The account root key
A key created by CloudHSM
No encryption is applied
kms:CreateAlias
kms:Decrypt and kms:GenerateDataKey
kms:ScheduleKeyDeletion
iam:CreateRole
47. How do you avoid Docker Hub rate limits in CodeBuild?
Anonymous Docker Hub pulls are rate limited per source IP, and CodeBuild builds share address ranges. The symptom is a toomanyrequests error while pulling a base image, often in PROVISIONING or during docker build.
Options, from most to least durable:
- Set up an ECR pull-through cache so images are fetched from ECR after the first pull.
- Mirror the base images you use into your own ECR repository, or use ECR Public copies.
- Authenticate to Docker Hub with credentials stored in Secrets Manager, using the project's registry credential setting or a
docker loginin pre_build. - Enable Docker layer caching so unchanged layers aren't re-pulled.
Raising the timeout or compute size won't help, since the limit is on pulls, not resources.
Take quiz
AccessDeniedException on ecr
toomanyrequests
YAML_FILE_ERROR
NoSuchBucket
Pull through an ECR cache or mirror the base images
Use a larger compute type
Disable privileged mode
Increase the build timeout
48. How do you produce multiple output artifacts in one build?
Use secondary-artifacts in the buildspec. Each entry has an identifier and its own files, base directory and name.
artifacts: secondary-artifacts: app: files: - '**/*' base-directory: dist coverage: files: - '**/*' base-directory: coverage-report
The identifiers app and coverage must match the secondary artifacts configured on the project, or the output artifact names in a CodePipeline action. Each artifact can go to a different S3 location. Secondary sources work similarly and appear in the build under CODEBUILD_SRC_DIR_<identifier>.
A typical use is publishing the deployable bundle as one artifact and the test or coverage output as another, so downstream stages pull only what they need.
Take quiz
artifacts.secondary-artifacts
artifacts.extra-files
artifacts.outputs
multi-artifacts
Report group ARNs
S3 bucket names
Git branch names
Those configured on the project or pipeline action
49. What happens when a command fails in a buildspec phase?
Any command that exits with a non-zero code fails its phase, and the build is marked FAILED. Later phases don't run as normal after an early failure.
You can change this with on-failure on a phase. ABORT stops the build, while CONTINUE lets the build carry on. A finally block always runs its commands, which makes it the right place for cleanup.
Notably, post_build still runs after a failed build phase, so guard deploy or push steps with CODEBUILD_BUILD_SUCCEEDING:
phases: build: on-failure: ABORT commands: - ./run-tests.sh post_build: commands: - if [ "$CODEBUILD_BUILD_SUCCEEDING" = "1" ]; then ./publish.sh; fi
Take quiz
CODEBUILD_EXIT_CODE
CODEBUILD_BUILD_SUCCEEDING
CODEBUILD_BUILD_STATUS
BUILD_OK
on-failure: CONTINUE
ignore-errors: true
set +e in the service role
continue-on-error: true
50. How do you apply least privilege to a CodeBuild service role?
Give each project its own role and scope every statement to the resources it truly uses. Avoid AdministratorAccess or PowerUserAccess on build roles, since build commands, and any dependency they pull in, run with those credentials.
- Logs: only the project's log group.
- S3: only the source, artifact and cache bucket prefixes needed.
- ECR: specific repositories, with
ecr:GetAuthorizationTokenon*because it can't be scoped to a resource. - Secrets and parameters: exact ARNs, plus the specific KMS key.
- VPC: network interface actions limited to the project's subnets.
{ "Effect": "Allow", "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"], "Resource": [ "arn:aws:logs:us-east-1:111122223333:log-group:/aws/codebuild/my-app", "arn:aws:logs:us-east-1:111122223333:log-group:/aws/codebuild/my-app:*" ] }
Add an aws:SourceArn condition in the trust policy to prevent confused-deputy use, and refine permissions over time using CloudTrail and IAM Access Analyzer. Keep deployment permissions in a separate role from the build role.