AWS CodeDeploy: How to Set Up a CI/CD Pipeline to Deploy Applications on EC2 Using GitHub

Deploying applications manually is tedious, error-prone, and inefficient. AWS CodeDeploy makes automating deployments straightforward, enhancing efficiency and minimizing downtime. In this guide, you'll learn step-by-step how to set up a robust Continuous Integration and Continuous Deployment (CI/CD) pipeline to deploy your applications directly from GitHub to an Amazon EC2 instance.

What You'll Need:


Step 1: Prepare Your EC2 Instance

Connect to your EC2 instance via SSH:

ssh -i "your-key.pem" ec2-user@your-ec2-instance-public-ip

Install and start the CodeDeploy agent:

sudo yum update
sudo yum install ruby -y
sudo yum install wget -y

cd /home/ec2-user
wget https://aws-codedeploy-region.s3.region.amazonaws.com/latest/install
chmod +x ./install
sudo ./install auto

sudo service codedeploy-agent status

Replace region with your AWS region, such as us-east-1.


Step 2: Create an IAM Role for CodeDeploy

In AWS Console:


Step 3: Set Up the CodeDeploy Application

Create a deployment group:


Step 4: Prepare Your GitHub Repository

Create an appspec.yml file at your repository root:

version: 0.0
os: linux
files:
  - source: /
    destination: /var/www/html
hooks:
  AfterInstall:
    - location: scripts/install_dependencies.sh
      timeout: 300
      runas: root

Create necessary scripts, e.g., scripts/install_dependencies.sh:

#!/bin/bash
sudo yum update -y
sudo yum install -y httpd
sudo service httpd start
sudo chkconfig httpd on

Make sure your scripts have execute permissions:

chmod +x scripts/*.sh

Commit and push changes to GitHub:

git add .
git commit -m "Added appspec.yml and deployment scripts"
git push origin main

Step 5: Connect AWS CodeDeploy with GitHub


Step 6: Automate with CI/CD Using GitHub Actions

Create .github/workflows/deploy.yml in your repo:

name: AWS Deploy

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: AWS CodeDeploy
        uses: aws-actions/aws-codedeploy@v1
        with:
          application-name: your-codedeploy-app-name
          deployment-group-name: your-deployment-group
          region: your-region
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

Set AWS credentials as GitHub secrets:

Now, every push to main triggers automatic deployments.


Step 7: Verify Your Deployment

Visit your EC2 public IP in a web browser:

http://your-ec2-instance-public-ip

You should see your application deployed successfully!


Conclusion

Congratulations! You've successfully set up an AWS CodeDeploy CI/CD pipeline integrated with GitHub to automatically deploy applications on EC2. This automation will significantly streamline your deployment process, reduce downtime, and simplify updates.