DEV Community

Charisse C. Lorejo
Charisse C. Lorejo

Posted on

Build an Automated AWS CI/CD Pipeline with CDK

This article will talk about how to automate the deployment of a modern React website using Amazon Web Services (AWS). Instead of manually deploying files, you will build an automated Continuous Integration and Continuous Deployment (CI/CD) pipeline. By the end of this session, every time you push code to GitHub, AWS will automatically test, build, and deploy your application to the internet.


The Concepts: DevOps and CI/CD

Before we build the infrastructure, let's look at why we need it.

A Brief History: The Problem of Silos

Before DevOps, a software development organization was typically split into two completely separate teams:

  1. The Development Team: Designs the system, plans how to build it, and writes the actual code.
  2. The Operations Team: Takes the code, tests it, checks for bugs, and manages the live servers. They send feedback back to the developers when things break.

The Problem: Because these teams were siloed, deadlocks occurred. When developers were writing code, operations sat idle. When operations was testing and deploying, developers had to wait for feedback. It created massive bottlenecks and endless "waiting for the other team" scenarios.

The Solution: DevOps


DevOps is a philosophy that breaks down the barrier between Development and Operations, transforming the software development lifecycle into a continuous, collaborative process.

It forms a continuous loop:

  • Plan & Code: The team plans the feature and writes the code, storing it in a version control system (like Git) so changes can be tracked or reverted.
  • Build & Test: The code is compiled into an executable format and automatically tested for bugs. If it passes, it's ready.
  • Deploy & Monitor: The code is deployed to the working environment (often using containers). The system is actively monitored for errors.
  • Feedback: Any issues or user behavior metrics are sent right back to the planning phase, and the cycle continues.

Automating the Cycle with CI/CD

DevOps is a great culture, but how do we make it fast and automatic? That is where CI/CD comes in.

  • Continuous Integration (CI): Developers commit code to a shared repository frequently. Every time they push a small commit, a CI server automatically builds the code and tells them if it was a success or failure. This avoids massive merge conflicts.
  • Continuous Deployment (CD): Once the code passes the CI checks, it is automatically deployed to the live environment without human intervention.

Mapping CI/CD to Our AWS Pipeline:
In this workshop, we will map this exact lifecycle to an automated AWS CodePipeline:

  • Source Stage: GitHub (Version control and storing our code).
  • Build & Test Stage: AWS CodeBuild (Our CI server that installs dependencies and builds the app).
  • Deploy Stage: AWS CodeDeploy / Amazon S3 / CloudFront (Where our live application lives and updates automatically).

Prerequisites

Before beginning the workshop, ensure you have the following ready:

  • A registered GitHub account
  • An active AWS Account
  • Node.js installed on your local machine (version 18 or higher recommended)
  • A code editor, such as Visual Studio Code

Step 1: Fork and Clone the Repository

To build a pipeline, you need your own copy of the source code so that AWS can detect your specific changes.

  1. Navigate to the workshop repository on GitHub:

    DevOps Workshop Game

    The DevOps Workshop Game is a full-stack, cloud-native Rock Paper Scissors application designed to demonstrate infrastructure as code (IaC) and CI/CD pipelines. This project features a React/Vite frontend and an AWS CDK-powered backend that fully automates the provisioning of S3 buckets, CloudFront CDN, and a CodePipeline for continuous deployment.

    Requirements & Installation

    To deploy and work with this project, you will need the following tools:

    • Node.js (v20 or higher recommended)
    • AWS CLI (configured with your AWS account credentials)
    • AWS CDK (npm install -g aws-cdk)
    • Git

    To set up the project locally:

    1. Clone the repository
      git clone <repository-url>
      cd devops-workshop-game
      Enter fullscreen mode Exit fullscreen mode
    2. Install the AWS CDK dependencies:
      npm install
      Enter fullscreen mode Exit fullscreen mode
    3. Update bin/devops-workshop-game.js with your AWS Account ID and preferred Region.
    4. Update the GitHub Source Action in lib/devops-workshop-game-stack.js with your GitHub username and configure your GitHub token in AWS Secrets Manager as workshop/github.

    Usage Guide

    To synthesize…

  2. Click the Fork button in the top right corner to create a copy of this repository in your personal GitHub account.
  3. Open your local terminal and clone your newly forked repository by running the following command (replace YOUR_USERNAME with your actual GitHub username):
git clone https://github.com/YOUR_USERNAME/devops-workshop-game.git
Enter fullscreen mode Exit fullscreen mode
  1. Change your directory into the cloned folder:
cd devops-workshop-game
Enter fullscreen mode Exit fullscreen mode

Step 2: Authenticate with AWS

Your local terminal requires explicit permission to interact with your AWS account and provision infrastructure.

Part A: Create an IAM User and Generate Access Keys

Since deploying infrastructure with CDK requires administrative permissions, you will first create a dedicated IAM user.

  1. Log in to the AWS Management Console.
  2. In the top search bar, search for IAM (Identity and Access Management) and select it.

  1. On the left-hand sidebar, click on Users, then click the Create user button.

  1. Enter a user name (e.g., workshop-admin) and click Next.
  2. On the permissions page, select Attach policies directly.
  3. In the permissions policies search bar, type AdministratorAccess. Check the box next to it and click Next.

  1. Review the details and click Create user.
  2. Back on the Users list, click on your newly created user (workshop-admin).
  3. Navigate to the Security credentials tab.

  1. Scroll down to the Access keys section and click Create access key.
  2. Select Command Line Interface (CLI) as the use case, acknowledge the warning, and click Next.

  1. Click Create access key. Leave this window open, as it displays your Secret Access Key which will never be shown again.

Part B: Configure the CLI

  1. Open your terminal and type:
aws configure
Enter fullscreen mode Exit fullscreen mode
  1. Enter the details exactly as prompted:
  2. AWS Access Key ID: (Copy and paste from the AWS webpage)
  3. AWS Secret Access Key: (Copy and paste from the AWS webpage)
  4. Default region name: ap-southeast-1
  5. Default output format: json

Step 3: Generate a GitHub Personal Access Token

AWS CodePipeline requires authorization to securely pull your source code from GitHub whenever a new commit is detected.

  1. Go to GitHub, click your profile picture in the top right, and select Settings.
  2. Scroll down the left sidebar and click Developer settings.
  3. Click Personal access tokens followed by Tokens (classic).

  1. Click Generate new token (classic).

  1. Name the token descriptively, such as "AWS Workshop Pipeline".
  2. Under Select scopes, check the box next to repo (This grants full control of private and public repositories).

  1. Scroll to the bottom and click Generate token.

  1. Copy the token immediately. It will start with ghp_. Store it temporarily in a secure location.

Step 4: Store Your Token Securely in AWS

Hardcoding security tokens in source code is a major security risk. You will use AWS Secrets Manager to store the token securely.

  1. In your terminal, run the following command. Replace <YOUR_TOKEN> with the exact token you copied from GitHub:
aws secretsmanager create-secret --name workshop/github --secret-string '{"token":"<YOUR_TOKEN>"}' --region ap-southeast-1
Enter fullscreen mode Exit fullscreen mode
  1. Upon success, the terminal will output a JSON block confirming the secret's creation.

Step 5: Install and Set Up AWS CDK

The AWS Cloud Development Kit (CDK) is a framework that allows you to define cloud infrastructure using familiar programming languages like JavaScript.

  1. Install the CDK globally on your machine using the Node Package Manager:
npm install -g aws-cdk
Enter fullscreen mode Exit fullscreen mode
  1. Verify that the installation was successful by checking the version:
cdk --version
Enter fullscreen mode Exit fullscreen mode
  1. Install the specific project dependencies required for this workshop:
npm install
Enter fullscreen mode Exit fullscreen mode

Step 6: Understanding the Infrastructure Code

Before connecting the pipeline, open lib/devops-workshop-game-stack.js. This file is the core of our "Infrastructure as Code" (IaC) setup. Instead of clicking through the AWS console, this JavaScript code defines exactly what cloud resources AWS needs to build for your app.

Here is a breakdown of what the code is doing:

  1. The Website Hosting Bucket: The websiteBucket object creates an Amazon S3 bucket configured specifically for static web hosting. Notice the blockPublicAccess section—we explicitly turn off the default security blocks so anyone on the internet can see your live game.

  1. The Global Content Delivery Network (CDN): To ensure game assets (like images) load instantly worldwide, the code provisions an AssetsBucket and pairs it with an AWS CloudFront distribution (AssetsCDN). It even uses BucketDeployment to automatically copy local files from ./frontend/src/assets directly into this bucket.
  2. The Automated Builder (CodeBuild): The buildProject definition acts as our temporary build server. It spins up a Linux container with Node.js 20, passes in the new CloudFront URL as an environment variable (VITE_CDN_URL), and runs npm run build to compile our Vite application.

It also automatically provisions IAM permissions to send build logs to Amazon CloudWatch.

  1. The Pipeline Orchestrator (CodePipeline): Finally, the WorkshopPipeline ties everything together into a three-stage workflow:
    • Source: Listens to your GitHub main branch and pulls code securely using the Secrets Manager token.
    • Build: Hands the fresh code to the CodeBuild project.
    • Deploy: Takes the finalized dist folder from the build output and places it in your public S3 Website Bucket.

Step 7: Connect Your Code to the Pipeline and Configure Environment

You must configure the infrastructure code to target your specific GitHub fork rather than the original repository, and set up your specific AWS account environment.

Part A: Update the Pipeline Stack

  1. Open the project folder in your code editor.
  2. Navigate to the file located at lib/devops-workshop-game-stack.js.
  3. Locate the GitHubSourceAction configuration block.
  4. Modify the owner field and output block to ensure it looks exactly like this:
actions: [
  new codepipeline_actions.GitHubSourceAction({
    actionName: 'GitHub_Source',
    owner: '<ENTER YOUR GITHUB USERNAME>',
    repo: 'devops-workshop-game',
    branch: 'main',
    // You will create a GitHub token and store it in AWS Secrets Manager
    oauthToken: SecretValue.secretsManager('workshop/github', { jsonField: 'token' }),
    output: sourceOutput,
  }),
],
Enter fullscreen mode Exit fullscreen mode
  1. Save the file.

Part B: Configure Your AWS Environment

  1. Navigate to the application entry point file, typically located at bin/devops-workshop-game.js.
  2. Locate the environment (env) configuration block.
  3. Update the account property to use your specific environment setup:
env: {
  account: '<ENTER ACCOUNT NUMBER>', // Your AWS Account ID from the ARN
  region: 'ap-southeast-1'  // The region where you created the secret
},
Enter fullscreen mode Exit fullscreen mode
  1. Save the file.

Step 8: Bootstrap and Deploy the Infrastructure

It is now time to compile your code into an AWS CloudFormation template and deploy it to the cloud.

  1. Bootstrap your AWS environment. Bootstrapping provisions initial resources (like Amazon S3 buckets and IAM roles) that the CDK needs to perform deployments. Replace <YOUR_AWS_ACCOUNT_ID> with your 12-digit AWS account number (found by clicking your name in the top right of the AWS console):
cdk bootstrap aws://<YOUR_AWS_ACCOUNT_ID>/ap-southeast-1
Enter fullscreen mode Exit fullscreen mode
  1. Once bootstrapping is complete, deploy the pipeline:
cdk deploy
Enter fullscreen mode Exit fullscreen mode
  1. The CLI will present a summary of security and IAM changes. Type y and press Enter to approve them.
  2. The initial deployment and build process will take several minutes to complete.

Step 9: Find Your Live App & Test the Workflow

Your pipeline is now active, and your application is hosted on an S3 bucket. You will now find your live URL and test the Continuous Deployment mechanism.

Part A: Find Your Live Website URL

You can access your website link using either the terminal or the AWS console.

Option 1: Via the AWS CLI (Terminal)

  1. List your S3 buckets to find the exact, unique name of your generated bucket:
aws s3 ls
Enter fullscreen mode Exit fullscreen mode

Look for a bucket name starting with devopsworkshopgamestack-websitebucket.

  1. Your live website URL follows this standard S3 format (replace <YOUR_BUCKET_NAME> with the exact name you found above): http://<YOUR_BUCKET_NAME>.s3-website.ap-southeast-1.amazonaws.com (Note: Make sure it is http:// and not https://)

Option 2: Via the AWS Console

  1. Open the AWS Console, navigate to the S3 service, and click on your new bucket.
  2. Select the Properties tab, scroll to the very bottom, and click the link under Static website hosting.

Part B: Test the Automation

  1. Return to your code editor and open frontend/src/App.jsx.
  2. Make a visible change to the application, such as modifying the title text or altering a Tailwind CSS color class.
  3. Save the file, commit the change, and push it to your GitHub repository:
git add .
git commit -m "Updated application title for deployment test"
git push origin main
Enter fullscreen mode Exit fullscreen mode
  1. Navigate to the AWS CodePipeline dashboard in your web browser. You will observe the pipeline automatically trigger, process the new code, rebuild the application, and update the live S3 website without any manual intervention.

Step 10: Clean Up Resources (Crucial)

Warning: To ensure you do not incur unwanted charges on your AWS account after the workshop, you must tear down the infrastructure you built.

1. Destroy the CDK Stack

This command will delete the S3 bucket, CodeBuild project, and CodePipeline. Run this in your terminal from the root of your project:

cdk destroy
Enter fullscreen mode Exit fullscreen mode

Type y and press Enter when asked to confirm the deletion.

2. Delete the Secret

The AWS CDK command does not delete secrets you created manually. Delete your GitHub token from AWS Secrets Manager by running:

aws secretsmanager delete-secret --secret-id workshop/github --force-delete-without-recovery --region ap-southeast-1
Enter fullscreen mode Exit fullscreen mode

3. Revoke the GitHub Token

Finally, practice good security hygiene by deleting the token from GitHub so it can never be used again.

  1. Go to GitHub > Settings > Developer settings > Personal access tokens > Tokens (classic).
  2. Find "AWS Workshop Pipeline" and click the Delete button next to it.

Top comments (0)