Step-by-Step Guide to Setting Up CI/CD with GitHub Actions

Why Use GitHub Actions for CI/CD?

  1. Ease of Integration: Built directly into GitHub, eliminating the need for third-party CI/CD tools.
  2. Extensive Marketplace: Leverage prebuilt actions for testing, building, and deploying.
  3. Custom Workflows: Define tailored workflows to suit your project’s needs.
  4. Cost-Effective: Free for public repositories and reasonable for private repositories.

Prerequisites

Before starting, ensure you have:

  • A GitHub repository (public or private).
  • Basic knowledge of YAML syntax.
  • Access to a cloud platform (e.g., AWS, Azure, or GCP) or server for deployments.

Step 1: Create a GitHub Repository

  1. Log in to GitHub and create a new repository.
  2. Clone the repository to your local machine and add your project files.
git clone https://github.com/<your-username>/<your-repo>.git

Step 2: Set Up a Workflow File

  1. Inside your project directory, create a folder named .github/workflows.
  2. Add a new YAML file, e.g., ci-cd.yml.
mkdir -p .github/workflows
touch .github/workflows/ci-cd.yml

## Step 3: Define Your Workflow

Open the ci-cd.yml file and add the following configuration:

```yaml
name: CI/CD Pipeline

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout Code
        uses: actions/checkout@v3

      - name: Set Up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 16

      - name: Install Dependencies
        run: npm install

      - name: Run Tests
        run: npm test

  deploy:
    needs: build
    runs-on: ubuntu-latest

    steps:
      - name: Deploy to Server
        run: |
          ssh user@your-server 'bash -s' < ./deploy.sh

Step 4: Add Secrets for Deployment

  1. Go to your repository settings in GitHub.
  2. Navigate to Secrets and variables > Actions.
  3. Add secrets for sensitive information (e.g., SSH keys, API tokens).

Step 5: Test Your Pipeline

  1. Push your code to the main branch:
git add .
git commit -m "Set up CI/CD pipeline"
git push origin main
  1. Check the Actions tab in GitHub to monitor the pipeline’s progress.

Step 6: Automate Deployment (Optional)

To automate deployment:

  1. Write a deploy.sh script with deployment commands (e.g., copying files, restarting services).
  2. Ensure the script is executable:
chmod +x deploy.sh

Best Practices for GitHub Actions

1. Use Cache:

  • Speed up builds by caching dependencies using actions/cache.
- name: Cache Node Modules
  uses: actions/cache@v3
  with:
    path: node_modules
    key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
    restore-keys: |
      ${{ runner.os }}-node-

2. Secure Secrets:

  • Use GitHub Secrets to store sensitive credentials securely.

3. Monitor Workflows:

  • Enable notifications for workflow failures to address issues quickly.