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.

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:

| Service | Job | Comparable tool |
|---|---|---|
| CodeCommit | Hosts private Git repositories | GitHub, Bitbucket |
| CodeArtifact | Stores software packages and build artifacts | Nexus, a Maven repository |
| CodeBuild | Compiles, tests and packages code in a temporary container | A Jenkins build job |
| CodeDeploy | Deploys a build to EC2, on-premises servers, Lambda or ECS | Jenkins deploy steps, Ansible |
| CodePipeline | Connects source, build, test and deploy into one pipeline | A 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.

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.

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.

Name the connection and click Connect to GitHub:

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


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:


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.

The code to build
The repository awscodebuild contains a single C++ file that prints a message:
#include <iostream>
int main()
{
std::cout << "Hello, DevOps!\n";
}Environment settings
The Environment section defines the machine that runs the build.
| Setting | Meaning | Lab value |
|---|---|---|
| Provisioning model | On-demand (start a machine per build) or reserved capacity (always-on fleet) | On-demand |
| Environment image | An image managed by AWS or your own Docker image | Managed image |
| Compute | EC2 or Lambda | EC2 |
| Running mode | Container or instance | Container |
| Operating system | Amazon Linux or Ubuntu | Ubuntu |
| Runtime and image | Standard runtime; pick the latest image version | Standard, latest |
| GPU-enhanced compute | For GPU workloads | Off |
| Service role | IAM role that CodeBuild uses to call other AWS services | New 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:
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.outThe 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).

- 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:GetObjectands3:PutObjecton 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:

Click Start build. The status shows In progress:

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


The Phase details tab shows how long each phase took:

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.

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.

console.log("Hello from AWS CodeBuild!");{
"name": "codebuild-demo",
"version": "1.0.0",
"scripts": {
"test": "echo \"Running tests...\" && exit 0"
}
}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 bucketThe same app as a Docker image. The Dockerfile:
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:
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.jsonKey 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 needsssm:GetParameters. CodeBuild hides these values in the logs. - To run
docker buildinside CodeBuild, turn on Privileged mode in the project's environment settings. imagedefinitions.jsontells 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:

Options for storing build secrets and variables:
| Option | Cost | Notes |
|---|---|---|
| SSM Parameter Store | Standard parameters have no extra charge | Use SecureString for passwords; reference with parameter-store |
| AWS Secrets Manager | Charged per secret per month | Adds automatic rotation; reference with secrets-manager |
Plain variables in the buildspec | Free | Visible 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.

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:
| Role | Trusted entity | Policies attached | Where it is used |
|---|---|---|---|
| EC2 instance role | AWS service: EC2 | AWSCodeDeployFullAccess, AmazonS3FullAccess | As the IAM instance profile in the launch template, so the CodeDeploy agent on each instance can download the app from S3 |
codedeployer | AWS service: CodeDeploy | AWSCodeDeployRole (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:

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

Deployment strategies
A deployment strategy defines how the new version replaces the old one. The same strategies apply on any platform, not only AWS.
| Strategy | How it works | Downtime | Cost | Rollback |
|---|---|---|---|---|
| In-place | Stop 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 update | Yes if all at once; reduced capacity if in batches | No extra servers | Redeploy the old version |
| Blue/green | Build a new environment (green) next to the live one (blue), test it, then switch traffic to green | Almost none | High: two environments for a while | Switch traffic back to blue |
| Canary | Send a small share of traffic (for example 10%) to the new version, wait, then send the rest | None | Low | Move traffic back if the canary fails |
| Linear | Shift traffic in equal steps (for example 10% every minute) until all traffic is on the new version | None | Low | Stop 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.



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.
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#!/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#!/bin/bash
service nginx start#!/bin/bash
isExistApp=$(pgrep nginx)
if [[ -n $isExistApp ]]; then
service nginx stop
fiThe 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.

- In User data, install the CodeDeploy agent so it starts on every new instance:
#!/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 installThe 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:

| Setting | Value |
|---|---|
| Service role | codedeployer |
| Deployment type | In-place |
| Environment configuration | Amazon EC2 Auto Scaling groups, then select the group created above |
| AWS Systems Manager agent install | Never (the agent is installed by user data) |
| Deployment settings | CodeDeployDefault.HalfAtATime |
| Load balancer | Enable 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.

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:

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.

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.

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

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 updatefails in the install phase with a GPG error: refresh the Corretto repository key as in the C++ buildspec above.docker buildfails inside CodeBuild: turn on Privileged mode in the environment.parameter-storevalues are empty or access is denied: addssm:GetParametersto 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 statusover 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; writeisExistApp=$(pgrep nginx). - Pipeline with an S3 source does not trigger: enable bucket versioning and the EventBridge rule.
Key takeaways
- CodeBuild runs
buildspec.ymlin a fresh container; CodeDeploy runsappspec.ymlthrough 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.
Keep reading
- Amazon EC2 Hands-On: Launch, Scale and Monitor Instances
Launch an EC2 instance and connect over SSH, then add a launch template, an Auto Scaling group, an Application Load Balancer and a CloudWatch alarm, with fixes for common errors.
- Build a Custom AWS VPC with Public and Private Subnets
Build a custom VPC step by step with an internet gateway, public and private subnets and a route table, then launch an EC2 instance and confirm what makes a subnet public.
- AWS Global Infrastructure and Core Services
How AWS Regions, Availability Zones and edge locations fit together, which services are global or regional, the main storage types, and the shared responsibility model.