Ace Cloud Interviews
Home/AWS Tutorial/CodeBuild
🛠️

AWS Developer Tools & CI/CD

CodeBuild

Fully managed build service that compiles source code, runs tests, and produces artifacts

AWS CodeBuild is a fully managed build service that compiles source code, runs unit tests, and produces deployment artifacts, eliminating the need to provision and manage build servers like Jenkins. It scales automatically - each build runs in a fresh, isolated container - so there are no queuing delays even during concurrent builds.

How CodeBuild Executes a Build

Every CodeBuild build follows a defined lifecycle. Understanding the phases is critical for debugging failed builds.

PhasePurposebuildspec.yml Key
SUBMITTEDBuild queued-
PROVISIONINGContainer starting up-
DOWNLOAD_SOURCESource code pulled from source provider-
INSTALLInstall dependencies and toolsinstall.commands
PRE_BUILDPre-build steps (login to ECR, etc.)pre_build.commands
BUILDCompile, test, packagebuild.commands
POST_BUILDPush artifacts, notificationspost_build.commands
UPLOAD_ARTIFACTSSend artifacts to S3artifacts section
FINALIZINGCleanup-
COMPLETEDBuild done-

The buildspec.yml file is the heart of CodeBuild. It lives at the root of your repository (or you can inline it in the project definition):

bash
version: 0.2

env:
  variables:
    NODE_ENV: "test"
  secrets-manager:
    DB_PASSWORD: "arn:aws:secretsmanager:us-east-1:123456789:secret:my-secret:password"

phases:
  install:
    runtime-versions:
      nodejs: 18
    commands:
      - npm ci
  pre_build:
    commands:
      - aws ecr get-login-password | docker login --username AWS --password-stdin $ECR_REPO
  build:
    commands:
      - npm run test
      - npm run build
      - docker build -t $ECR_REPO:$CODEBUILD_RESOLVED_SOURCE_VERSION .
      - docker push $ECR_REPO:$CODEBUILD_RESOLVED_SOURCE_VERSION
  post_build:
    commands:
      - echo "Build complete"

artifacts:
  files:
    - '**/*'
  base-directory: dist

cache:
  paths:
    - node_modules/**/*

Compute Types and Build Environments

CodeBuild offers several compute options. Choosing the right size directly affects build duration and cost.

Compute TypevCPUMemoryDiskUse Case
BUILD_GENERAL1_SMALL34 GB64 GBSimple builds, linting, unit tests
BUILD_GENERAL1_MEDIUM716 GB128 GBMost application builds
BUILD_GENERAL1_LARGE832 GB128 GBHeavy builds, Docker, parallel tests
BUILD_GENERAL1_2XLARGE72144 GB824 GBGPU builds, large monorepos
BUILD_LAMBDA_1GBN/A1 GB512 MBFast Lambda-backed builds (lower cold start)

For the build environment image, AWS provides curated images (aws/codebuild/standard:7.0 for latest) or you can bring your own Docker image from ECR or Docker Hub. Custom images let you pre-install tools to reduce install phase time.

💡

If your build needs to run Docker commands (docker build, docker push), enable "Privileged mode" on the build project. Without this, the Docker daemon is not available inside the build container.

Build Caching Strategies

CodeBuild supports three caching mechanisms. Caching is one of the most impactful optimizations for build speed.

Cache TypeHow It WorksBest ForInvalidation
S3 cacheTar and upload specified paths to S3 between buildsnode_modules, .m2, pip cacheManual or cache key change
Local cacheReuse layers in the build container (same fleet)Docker layer cache, custom sourcePer-fleet, not guaranteed
Local + S3Local first, fall back to S3Highest hit rateBoth mechanisms

Define the cache in buildspec.yml under the cache key. S3 cache paths are compressed and stored as zip files named by a hash of the cache key.

bash
# In buildspec.yml - cache node_modules to S3
cache:
  paths:
    - node_modules/**/*
    - .npm/**/*

# In CodeBuild project (console/Terraform) - enable S3 cache
# cache:
#   type: S3
#   location: my-bucket/codebuild-cache
⚠️

S3 caching adds upload/download time at the start and end of each build. For small projects, this overhead can exceed the time saved. Benchmark with and without cache to confirm it helps.

VPC Access, IAM, and Secrets

By default, CodeBuild runs in an AWS-managed network with internet access. When builds need to reach resources inside your VPC (RDS, internal APIs, Elasticache), you must configure VPC mode.

RequirementConfiguration
Access RDS or internal servicesEnable VPC mode - specify VPC, subnets, security group
Outbound internet in VPC modePrivate subnets must have a NAT Gateway
Pull from ECR in VPC modeECR VPC endpoint OR NAT Gateway
Read Secrets ManagerIAM role permission + optionally Secrets Manager VPC endpoint
Access S3 artifactsS3 VPC endpoint recommended (avoids NAT costs)

The CodeBuild service role needs permissions for everything the build does. Common additions beyond the AWS-managed policy:

bash
# Common IAM additions for CodeBuild service role
# ECR push/pull
ecr:GetAuthorizationToken
ecr:BatchCheckLayerAvailability
ecr:InitiateLayerUpload
ecr:UploadLayerPart
ecr:CompleteLayerUpload
ecr:PutImage

# Secrets Manager
secretsmanager:GetSecretValue

# Parameter Store
ssm:GetParameters
ssm:GetParametersByPath

# S3 artifact bucket
s3:GetObject
s3:PutObject
s3:GetBucketAcl
s3:GetBucketLocation
💡

Never put secrets in environment variables as plaintext in the project definition - they appear in build logs. Always use Secrets Manager or Parameter Store with the secrets-manager or parameter-store keys in buildspec.yml env section.

Pricing Model and Cost Optimization

Compute TypePrice per Build Minute
BUILD_GENERAL1_SMALL (Linux)$0.005
BUILD_GENERAL1_MEDIUM (Linux)$0.010
BUILD_GENERAL1_LARGE (Linux)$0.020
BUILD_GENERAL1_2XLARGE (Linux)$0.080
BUILD_GENERAL1_SMALL (Windows)$0.011
BUILD_LAMBDA_1GB$0.00002 per second

Billing is per minute, rounded up. The free tier includes 100 build minutes per month on BUILD_GENERAL1_SMALL.

Cost optimization strategies: use S3 caching to reduce build duration; use the smallest compute type that completes within an acceptable time; parallelize test suites using batch builds rather than running them sequentially.

🎯

Interview Focus Points

  • 1What are the phases of a CodeBuild build and what happens in each phase?
  • 2How do you pass secrets to a CodeBuild build without exposing them in logs?
  • 3When would you use a custom Docker image vs the AWS standard image?
  • 4What is privileged mode and when is it required?
  • 5How does CodeBuild VPC mode work and what network components are required?
  • 6What caching strategies does CodeBuild support and what are the trade-offs?
  • 7How do you run Docker builds inside CodeBuild?
  • 8How would you configure CodeBuild to run tests in parallel?
  • 9How does CodeBuild pricing work - what are you actually billed for?