Skip to content
DBDeependra Bhatta~/notes
Cloud & AWS#aws-developer-tools · #aws · #docker · #ec2 · #load-balancing · #auto-scaling

AWS CodeBuild, CodeDeploy and CodePipeline Hands-On

Build code with AWS CodeBuild and a buildspec.yml, deploy it to an Auto Scaling group with CodeDeploy, and connect both into a pipeline with AWS CodePipeline.

· updated · 21 min read
ON THIS PAGE

AWS ships its own CI/CD services, the "Code" tools, which cover the same ground as GitHub, Nexus and Jenkins but run fully managed inside your AWS account. This guide compiles a small C++ program with CodeBuild, deploys a web app to an Auto Scaling group with CodeDeploy, and connects the stages with CodePipeline. It also covers the IAM roles each service needs and the main deployment strategies, so you can write a buildspec.yml and an appspec.yml and run a first deployment on EC2.

Prerequisites

  • An AWS account with permission to manage IAM roles, S3, EC2, CodeBuild, CodeDeploy and CodePipeline.
  • A GitHub account with a repository to build.
  • An S3 bucket for build artifacts and deployment bundles.
  • Familiarity with launch templates, Auto Scaling groups and load balancers from Amazon EC2.

The tools at a glance

In the console, all five services sit under Developer Tools:

AWS Developer Tools menu listing Source CodeCommit, Artifacts CodeArtifact, Build CodeBuild, Deploy CodeDeploy, Pipeline CodePipeline

ServiceJobComparable tool
CodeCommitHosts private Git repositoriesGitHub, Bitbucket
CodeArtifactStores software packages and build artifactsNexus, a Maven repository
CodeBuildCompiles, tests and packages code in a temporary containerA Jenkins build job
CodeDeployDeploys a build to EC2, on-premises servers, Lambda or ECSJenkins deploy steps, Ansible
CodePipelineConnects source, build, test and deploy into one pipelineA Jenkins pipeline

All five integrate with IAM for permissions and with CloudWatch for logs.

CodeCommit

CodeCommit is a managed Git service. Repositories live in your AWS account, are encrypted at rest and in transit, and use IAM users and roles for access instead of separate Git accounts. Standard git commands work against them.

CodeArtifact

CodeArtifact is a managed artifact repository, the AWS counterpart to the Nexus setup in SonarQube and Nexus. It stores packages such as JAR and WAR files from Maven or Gradle, npm packages and Python packages, and works with the standard package managers (mvn, gradle, npm, yarn, pip, twine).

It has two main components:

  • Domain: groups repositories and applies access policies across multiple AWS accounts in an organization.
  • Repository: holds the packages. A repository can pull from public registries (such as Maven Central or npmjs) as an upstream source and cache what it downloads.

CodeArtifact flow: public repositories feed CodeArtifact domains and repositories, used by developers and CodeBuild

You pay for storage, requests and data transferred out of the Region. There is no license fee.

CodeBuild

CodeBuild runs build commands in a fresh container each time. There is no build server to install, patch or scale, and billing covers only the build minutes used. CodeBuild handles CI (continuous integration): turning source code into a tested artifact.

The build instructions live in buildspec.yml, which plays the same role as a Jenkinsfile (see Jenkins pipelines).

Create a build project and connect GitHub

Open Developer Tools > CodeBuild > Build projects > Create build project. Name the project (this lab uses Dipen_demoproject) and choose Default project, a custom project built from scratch. The other type, Runner project, uses CodeBuild as a managed runner for GitHub Actions, GitLab or Buildkite.

The Source provider options are no source, GitHub, GitHub Enterprise Server, Bitbucket, GitLab, GitLab Self Managed, Amazon S3 and CodeCommit. "No source" resembles a Jenkins freestyle job in which the commands clone the code themselves. Choose GitHub. Until AWS is authorized to access your GitHub account, the console shows an error.

Create build project form with project name Dipen_demoproject, source GitHub and the error You have not connected to GitHub

Click Manage account credentials. Choose GitHub App as the credential type (the other options are a personal access token or an OAuth app), then click create a new GitHub connection.

Manage default source credential dialog with GitHub App selected and the create a new GitHub connection link

Name the connection and click Connect to GitHub:

Create a connection page with connection name demo-github_connection-dipendra and the Connect to GitHub button

Then click Install a new app to install the AWS Connector for GitHub app on your GitHub account or organization.

GitHub connection settings with the Install a new app button highlighted

GitHub page Install AWS Connector for GitHub asking which account or organization to install it on

Choose the account, approve with MFA if prompted, and select the repositories AWS may access. Back in AWS, the connection shows as Available, and the build project reports the account as connected:

Developer Tools Connections list with a GitHub connection in Available status

CodeBuild credential message: account successfully connected using an AWS managed GitHub App

Next, pick the repository. The options are Repository in my GitHub account, Public repository (paste a URL, as in Jenkins) or a GitHub scoped webhook. Source version accepts a branch, tag or commit ID to build.

Repository selection with Repository in my GitHub account chosen and the awscodebuild repository listed

The code to build

The repository awscodebuild contains a single C++ file that prints a message:

CPPhello.cpp
#include <iostream>
 
int main()
{
  std::cout << "Hello, DevOps!\n";
}

Environment settings

The Environment section defines the machine that runs the build.

SettingMeaningLab value
Provisioning modelOn-demand (start a machine per build) or reserved capacity (always-on fleet)On-demand
Environment imageAn image managed by AWS or your own Docker imageManaged image
ComputeEC2 or LambdaEC2
Running modeContainer or instanceContainer
Operating systemAmazon Linux or UbuntuUbuntu
Runtime and imageStandard runtime; pick the latest image versionStandard, latest
GPU-enhanced computeFor GPU workloadsOff
Service roleIAM role that CodeBuild uses to call other AWS servicesNew service role

The service role lets CodeBuild act on your behalf: write logs to CloudWatch, read the source, and upload artifacts to S3. With New service role, the console creates the role and attaches the required permissions. Whenever one AWS service calls another, it does so through an IAM role (see AWS IAM).

buildspec.yml

Under Buildspec, either enter the commands in the console or use a buildspec.yml file from the repository. By default CodeBuild looks for buildspec.yml in the repository root; enter a different name or path here if needed. The buildspec for the C++ program:

YMLbuildspec.yml
version: 0.2            # buildspec format version; always use 0.2
 
phases:                 # the steps CodeBuild runs, in order
  install:              # install tools the build needs
    commands:
      - rm -f /usr/share/keyrings/corretto-keyring.gpg
      - wget -O - https://apt.corretto.aws/corretto.key | gpg --dearmor -o /etc/apt/trusted.gpg.d/corretto-keyring.gpg
      - apt-get update -y
      - apt-get install -y build-essential
  build:                # compile the code
    commands:
      - echo Build started on `date`
      - echo Compiling the C++ code...
      - g++ hello.cpp -o hello.out
  post_build:           # runs after the build phase
    commands:
      - echo Build completed on `date`
 
artifacts:              # files to keep after the build
  files:
    - hello.out

The first two install commands replace the Amazon Corretto (Java) repository signing key on the build image. Without a valid key, apt-get update can fail with a GPG signature error and stop the build before it starts. build-essential installs g++.

The phase names are fixed: install, pre_build, build and post_build. See the buildspec reference for all options.

Artifacts and logs

Under Artifacts, choose Amazon S3 to store the build output (the default is No artifacts).

Artifact 1 Primary type dropdown with Amazon S3 and No artifacts options

  • Bucket name: an S3 bucket you created for artifacts.
  • Name: an optional folder name inside the bucket. This lab leaves it empty.
  • Artifacts packaging: Zip.
  • The service role needs s3:GetObject and s3:PutObject on that bucket. The console adds this when it creates the role.

Under Logs, keep CloudWatch logs turned on so every build log is saved. Then click Create build project.

Run the build

The project page provides actions to start a build, edit or clone the project, debug a build, or start a build with overrides:

demo-codebuild project page with Actions, Create trigger, Edit, Clone, Debug build and Start build buttons

Click Start build. The status shows In progress:

CodeBuild build status In progress with build number 1 and the Build logs tab

The Build logs tab shows each command from the buildspec as it runs:

CodeBuild log showing DOWNLOAD_SOURCE succeeded, three phases found, and the INSTALL phase commands running

CodeBuild log with BUILD, POST_BUILD and UPLOAD_ARTIFACTS phases all SUCCEEDED and hello.out found

The Phase details tab shows how long each phase took:

CodeBuild phase details: SUBMITTED, QUEUED, PROVISIONING, DOWNLOAD_SOURCE, INSTALL, PRE_BUILD and BUILD all succeeded

The project page also provides:

  • Triggers: run builds on a schedule, with a cron expression or a fixed rate.
  • Reports: test and code coverage reports.
  • Notifications: send build events (started, succeeded, failed) to an SNS topic, or to Slack and Microsoft Teams.
  • Clone: copy the project to test changes without modifying the original.

CodeBuild Create trigger form with a cron-based schedule

The console also links CodeBuild integrations for Jenkins, GitHub Actions and GitLab runners, which use CodeBuild as the build engine for those tools.

More buildspec examples

A Node.js app. The repository has three files: buildspec.yml, index.js and package.json.

Repository folder with buildspec.yml, index.js and package.json for the Node.js app

JSindex.js
console.log("Hello from AWS CodeBuild!");
{}package.json
{
  "name": "codebuild-demo",
  "version": "1.0.0",
  "scripts": {
    "test": "echo \"Running tests...\" && exit 0"
  }
}
YMLbuildspec.yml
version: 0.2
 
phases:
  install:
    commands:
      - echo Installing dependencies...
      - npm install            # installs the dependencies from package.json
  build:
    commands:
      - echo Running tests...
      - npm test
      - echo Packaging application...
      - zip -r app.zip .       # package the app as one zip file
 
artifacts:
  files:
    - app.zip                  # uploaded to the S3 artifact bucket

The same app as a Docker image. The Dockerfile:

DKRDockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["node", "index.js"]

This buildspec logs in to Docker Hub, builds the image, tags it with the first 7 characters of the commit ID, and pushes it:

YMLbuildspec.yml
version: 0.2
 
env:
  parameter-store:                       # read from SSM Parameter Store
    DOCKERHUB_USERNAME: "DOCKERHUB_USERNAME"
    DOCKERHUB_PASSWORD: "DOCKERHUB_PASSWORD"
  variables:
    IMAGE_REPO_NAME: "your-dockerhub-user/node-app-aws"
    AWS_REGION: "us-east-1"
 
phases:
  pre_build:
    commands:
      - echo Logging in to Docker Hub...
      - echo $DOCKERHUB_PASSWORD | docker login -u $DOCKERHUB_USERNAME --password-stdin
      - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
      - IMAGE_TAG=${COMMIT_HASH:=latest}
  build:
    commands:
      - echo Building the Docker image...
      - docker build -t $IMAGE_REPO_NAME:$IMAGE_TAG .
  post_build:
    commands:
      - echo Pushing the Docker image to Docker Hub...
      - docker push $IMAGE_REPO_NAME:$IMAGE_TAG
      - echo Writing image definitions file...
      - printf '[{"name":"nodejs-app","imageUri":"%s"}]' $IMAGE_REPO_NAME:$IMAGE_TAG > imagedefinitions.json
 
artifacts:
  files: imagedefinitions.json

Key points in this example:

  • Under parameter-store, the left side is the variable name used in the build and the right side is the name of the parameter in SSM Parameter Store, not the secret itself. The service role needs ssm:GetParameters. CodeBuild hides these values in the logs.
  • To run docker build inside CodeBuild, turn on Privileged mode in the project's environment settings.
  • imagedefinitions.json tells CodePipeline's Amazon ECS deploy action which image to run. It is required only when deploying to ECS through CodePipeline.
  • The lab pushes to Docker Hub instead of Amazon ECR (Elastic Container Registry) to avoid ECR storage costs. In production on AWS, ECR is the natural choice because it uses IAM for access. The private ECR repository form:

Amazon ECR Create a private repository form with repository name, image tag mutability and encryption settings

Options for storing build secrets and variables:

OptionCostNotes
SSM Parameter StoreStandard parameters have no extra chargeUse SecureString for passwords; reference with parameter-store
AWS Secrets ManagerCharged per secret per monthAdds automatic rotation; reference with secrets-manager
Plain variables in the buildspecFreeVisible to anyone who can read the project; never use for secrets

For Docker basics and registries, see Dockerfile and registries.

CodeDeploy

CodeDeploy takes a build from S3 or GitHub and installs it on your servers in a controlled way. It deploys to EC2 instances, on-premises servers, AWS Lambda and Amazon ECS, and handles CD (continuous delivery).

CodeDeploy is free for EC2 and Lambda deployments and costs $0.02 per instance update for on-premises servers. The EC2 instances, load balancer and S3 storage are billed as usual.

Create an application

Open Developer Tools > CodeDeploy > Applications > Create application. Name the application (demo-applications here) and choose the EC2/on-premises compute platform.

CodeDeploy Create application form with name demo-applications and compute platform EC2/on-premises

The next steps are a deployment group (the set of servers to deploy to) and then deployments. Both depend on two IAM roles.

The two IAM roles

CodeDeploy on EC2 needs two different roles, a frequent source of confusion:

RoleTrusted entityPolicies attachedWhere it is used
EC2 instance roleAWS service: EC2AWSCodeDeployFullAccess, AmazonS3FullAccessAs the IAM instance profile in the launch template, so the CodeDeploy agent on each instance can download the app from S3
codedeployerAWS service: CodeDeployAWSCodeDeployRole (added by the CodeDeploy use case)As the service role of the deployment group, so CodeDeploy can work with EC2, Auto Scaling and load balancers

Create both in IAM > Roles > Create role > AWS service. For the first role, choose the EC2 use case:

IAM create role with service EC2 and use case EC2 selected

For the second, choose CodeDeploy as both the service and the use case:

IAM create role with service CodeDeploy and use case CodeDeploy selected

Deployment strategies

A deployment strategy defines how the new version replaces the old one. The same strategies apply on any platform, not only AWS.

StrategyHow it worksDowntimeCostRollback
In-placeStop the app on the existing servers, install the new version, start it again. With all servers at once it is the same as the Kubernetes "recreate" strategy; in batches it becomes a rolling updateYes if all at once; reduced capacity if in batchesNo extra serversRedeploy the old version
Blue/greenBuild a new environment (green) next to the live one (blue), test it, then switch traffic to greenAlmost noneHigh: two environments for a whileSwitch traffic back to blue
CanarySend a small share of traffic (for example 10%) to the new version, wait, then send the restNoneLowMove traffic back if the canary fails
LinearShift traffic in equal steps (for example 10% every minute) until all traffic is on the new versionNoneLowStop and shift traffic back

In CodeDeploy, the EC2/on-premises platform supports in-place and blue/green, with the batch sizes CodeDeployDefault.AllAtOnce, HalfAtATime and OneAtATime (the default is OneAtATime). Canary and linear traffic shifting are available for Lambda and ECS deployments.

Blue/green deployment: two identical environments with database, application and web servers; users switch from blue to green

Rolling update: three v1 instances replaced one by one until all three run v2

Canary deployment: load balancer sends most users to version 1 and a few to version 2, then all to version 2

A typical canary release is a large social network enabling a new feature for users in one region, watching for errors, and then rolling it out everywhere.

appspec.yml and scripts

CodeDeploy reads appspec.yml from the root of the app bundle. It is the deployment counterpart of buildspec.yml: it defines which files to copy where, and which scripts to run at each lifecycle hook. The sample app installs nginx and serves a page with the server's hostname and IP, which shows the instance the load balancer selected.

YMLappspec.yml
version: 0.0                    # the only valid appspec version
os: linux
files:
  - source: /                   # copy the whole bundle...
    destination: /var/www/html/ # ...to the nginx web root
hooks:
  BeforeInstall:
    - location: scripts/install_dependencies
      timeout: 300
      runas: root
    - location: scripts/start_server
      timeout: 300
      runas: root
  ApplicationStop:
    - location: scripts/stop_server
      timeout: 300
      runas: root
SHinstall_dependencies
scriptsinstall_dependencies
#!/bin/bash
apt-get install -y nginx
 
echo "<h1>Server Details</h1><p><strong>Hostname:</strong> $(hostname)</p><p><strong>IP Address:</strong> $(hostname -I | cut -d" " -f1)</p>" > /var/www/html/index.html
SHstart_server
scriptsstart_server
#!/bin/bash
service nginx start
SHstop_server
scriptsstop_server
#!/bin/bash
isExistApp=$(pgrep nginx)
if [[ -n $isExistApp ]]; then
    service nginx stop
fi

The complete app is in the devops_app repository. Clone it, zip it, and upload the zip to an S3 bucket.

Infrastructure: load balancer, launch template, Auto Scaling group

Amazon EC2 covers these three components in detail. Only the settings that matter for CodeDeploy are listed here.

Application Load Balancer

  • Internet-facing, IPv4, default VPC, all Availability Zones.
  • Security group allows HTTP (port 80) from anywhere.
  • A new target group for the instances.

Launch template

  • Attach a key pair. It is optional, but SSH access is essential for reading the agent logs when a deployment fails.
  • Under Advanced details > IAM instance profile, select the EC2 instance role from above.

Launch template Advanced details with the IAM instance profile field where the CodeDeploy instance role is attached

  • In User data, install the CodeDeploy agent so it starts on every new instance:
SHuser-data.sh
#!/bin/bash
sudo apt-get update -y
sudo apt-get install ruby -y
sudo apt-get install wget -y
cd /home/ubuntu
wget https://aws-codedeploy-us-east-1.s3.amazonaws.com/latest/install
chmod +x ./install
sudo ./install auto
service codedeploy-agent start
rm install

The installer URL contains the Region (us-east-1 here); use the bucket for your own Region.

Auto Scaling group

  • Use the launch template (default version), default VPC and the Availability Zones you need.
  • Attach it to the load balancer's target group.
  • Group size: desired 2, minimum 1, maximum 2.

Create the deployment group

In the application, create a deployment group:

Deployment group name and service role fields with the codedeployer role ARN selected

SettingValue
Service rolecodedeployer
Deployment typeIn-place
Environment configurationAmazon EC2 Auto Scaling groups, then select the group created above
AWS Systems Manager agent installNever (the agent is installed by user data)
Deployment settingsCodeDeployDefault.HalfAtATime
Load balancerEnable load balancing, Application Load Balancer, select the target group

A deployment group can also target plain EC2 instances by tag, or on-premises servers, instead of an Auto Scaling group.

Deployment configuration dropdown with OneAtATime, HalfAtATime and AllAtOnce, and load balancing enabled

With 3 instances, AllAtOnce updates all three together, HalfAtATime updates at most one at a time (half, rounded down), and OneAtATime updates them one by one. While an instance is being updated, the load balancer stops sending it traffic.

Create a deployment

In the deployment group, click Create deployment:

  • Revision type: My application is stored in Amazon S3.
  • Revision location: open the bucket in S3, select the zip file, click Copy S3 URI and paste it (s3://bucket-name/file.zip).
  • Revision file type: .zip.

Click Create deployment, then View events to follow each lifecycle event on each instance:

CodeDeploy deployment lifecycle events all Succeeded, one taking 5 minutes 10 seconds

When the deployment finishes, the load balancer DNS name (or an instance's public IP) serves the server details page, and refreshing it alternates between the two instances. The deployment page can also stop a running deployment or roll back to the previous revision.

To ship a change, upload a new zip to S3 and create a new deployment. CodePipeline automates this step.

CodePipeline

CodePipeline connects the stages into one flow: source → build → test → deploy. When the source changes, the pipeline runs automatically.

Open CodePipeline > Create pipeline. The console offers templates (push to ECR, deploy to ECS Fargate, CloudFormation, Terraform); choose Build custom pipeline.

CodePipeline category and template options including Deployment, Continuous Integration, Automation and Build custom pipeline

Pipeline settings: name demo-deependra-pipeline, execution mode Queued (runs wait in line instead of replacing each other), and let CodePipeline create a new service role.

Pipeline settings with name demo-deependra-pipeline, execution mode Queued and a new service role

Source stage: provider Amazon S3, the bucket that holds the code, and the object key of the zip file.

CodePipeline source stage with Amazon S3 provider, bucket name and S3 object key devops_app.zip

The option Create EventBridge rule to automatically detect source changes starts the pipeline whenever a new zip is uploaded. For a first test, turn it off and start the pipeline manually.

The remaining stages:

  • Build: optional, and skipped here because the zip is already built. This is where the CodeBuild project goes.
  • Test: optional; several test providers are available. Skipped here.
  • Deploy: provider AWS CodeDeploy, then select the application and deployment group from above.

Click Create pipeline. The pipeline view shows every stage and its status. If a stage fails, fix the problem and retry that stage alone instead of rerunning the whole pipeline.

Common mistakes

  • "You have not connected to GitHub" in CodeBuild: create a GitHub App connection and install the AWS Connector for GitHub on the account first.
  • apt-get update fails in the install phase with a GPG error: refresh the Corretto repository key as in the C++ buildspec above.
  • docker build fails inside CodeBuild: turn on Privileged mode in the environment.
  • parameter-store values are empty or access is denied: add ssm:GetParameters to the CodeBuild service role.
  • CodeDeploy deployment hangs or fails on every instance: the CodeDeploy agent is usually not running, or the instance has no instance profile allowing S3 access. Check service codedeploy-agent status over SSH.
  • Mixing up the two roles: the EC2 role goes in the launch template; the CodeDeploy role goes in the deployment group.
  • Shell script syntax: isExistApp = $(pgrep nginx) with spaces is a bash error; write isExistApp=$(pgrep nginx).
  • Pipeline with an S3 source does not trigger: enable bucket versioning and the EventBridge rule.

Key takeaways

  • CodeBuild runs buildspec.yml in a fresh container; CodeDeploy runs appspec.yml through the agent on each server.
  • Every AWS service that calls another one needs an IAM role. CodeDeploy on EC2 needs two: an instance role and a service role.
  • On EC2, CodeDeploy does in-place or blue/green with AllAtOnce, HalfAtATime or OneAtATime; canary and linear are for Lambda and ECS.
  • Keep secrets in SSM Parameter Store or Secrets Manager, never as plain buildspec variables.
  • CodePipeline ties source, build, test and deploy together; an S3 source needs bucket versioning.

This is the final part of the AWS hands-on series. Start from the beginning with AWS IAM.