Writing

Getting Started with CI/CD: Automating Your First Pipeline (with GitHub Actions)

21/09/24

Why This Guide? 🎯

If you've ever thought "I wish I could automate this" while working on a project, you're in the right place. This guide will take you from complete beginner to having a working CI/CD pipeline using GitHub Actions. No prior DevOps experience required!



What We'll Build 🛠️

By the end of this guide, you'll have:

  • A working CI/CD pipeline
  • Automated tests and deployments
  • Real-world examples you can adapt
  • Practical knowledge of GitHub Actions



Prerequisites 📋

Before we get started, here's a quick list of what you need:

  • A GitHub account (free tier is fine)
  • Basic command line knowledge
  • Node.js installed on your computer
  • Git installed on your computer



Part 1: Understanding GitHub Actions 🤔

What Are GitHub Actions, Really?

Imagine having a helpful robot that watches your GitHub repository and automatically does tasks whenever something happens. That's GitHub Actions in a nutshell.

Real-world example: You push some code to your repository, and automatically:

  1. Tests run to check if anything broke
  2. Code gets formatted according to your team's style
  3. A preview version gets deployed
  4. You get a Slack notification about the deployment

All of this happens without you lifting a finger!



Key Terms (The Important Stuff)

Instead of dry definitions, let's understand these through examples:

  1. Workflow (The Recipe)
 name: Deploy Website
 on: [push]  # When to run
 jobs:       # What to do
   test:
     runs-on: ubuntu-latest
  1. Event (The Trigger)
- Push code? That is an event
- Create a pull request? That is an event
- Schedule a daily backup? Also an event
  1. Job (The Task List)
- Like a checklist of things to do
- Runs independently
- Can depend on other jobs
  1. Step (The Individual Action)
- Single commands or actions
- Like `npm install` or `run tests`



Part 2: Your First Workflow 🚀

Step 1: Create a GitHub Repository 📦

Before we dive into creating your pipeline, let's first create a GitHub repository to hold your project.

1.1. Create the Repository

  • Go to GitHub and log in.
  • Click the + button in the top right corner and select New repository.
  • Name your repository (e.g., my-first-pipeline).
  • Choose the Public option.
  • Click Create repository.



Step 2: Clone the Repository Locally 💻

Now that we have a repository, let's clone it to your local machine.

git clone https://github.com/your-username/my-first-pipeline.git
cd my-first-pipeline


Let's create something practical: a workflow that tests a Node.js application.

2.1. Create the Project Structure

mkdir my-first-action
cd my-first-action
npm init -y
2.2. Add a Simple Calculator Function

Create src/calculator.js:

class Calculator {
  add(a, b) { return a + b; }
  subtract(a, b) { return a - b; }
}
module.exports = Calculator;
2.3. Add Tests

Create tests/calculator.test.js:

const Calculator = require('../src/calculator');

test('adds 1 + 2 to equal 3', () => {
  const calc = new Calculator();
  expect(calc.add(1, 2)).toBe(3);
});


2.4. Create Your First Workflow

Create .github/workflows/test.yml:

name: Run Tests

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '20'
          cache: 'npm'
      
      - name: Install dependencies
        run: npm install
      
      - name: Run tests
        run: npm test


Part 3: Git Commands - Add, Commit, and Push 🧑‍💻

Now that we have the project structure and workflow set up, let's connect everything to GitHub and push our changes.

3.1. Add Files to Git

Add the files to Git:

git add .
3.2. Commit Your Changes

Commit your changes with a meaningful message:

git commit -m "Add Node.js project with simple calculator and test"
3.3. Push to GitHub

Push your changes to GitHub:

git push origin main

🎉 Congratulations! You've just pushed your code to GitHub, and that means you've set up your very first CI/CD pipeline. The next time you push changes to this repository, GitHub Actions will automatically run the tests for you. 🎉



Part 4: Real-World Examples 🌟

Example 1: Automated Pull Request Checks
name: PR Checks

on:
  pull_request:
    branches: [ main ]

jobs:
  quality:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        
      - name: Install dependencies
        run: npm ci
      
      - name: Check formatting
        run: npx prettier --check .
      
      - name: Run linter
        run: npx eslint .
      
      - name: Run tests
        run: npm test


Example 2: Automated Deployments

name: Deploy to Production

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
      
      - name: Install dependencies
        run: npm ci
      
      - name: Build
        run: npm run build
      
      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./dist


Part 5: Advanced Features 🔧

Environment Variables and Secrets
jobs:
  deploy:
    env:
      NODE_ENV: production
    steps:
      - name: Deploy
        env:
          API_KEY: ${{ secrets.API_KEY }}
        run: npm run deploy


Matrix Builds (Testing Multiple Versions)
jobs:
  test:
    strategy:
      matrix:
        node-version: [16.x, 18.x, 20.x]
    steps:
      - uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.node-version }}


Part 6: Best Practices 📚

  1. Cache Dependencies

    - uses: actions/cache@v3
      with:
        path: ~/.npm
        key: npm-${{ hashFiles('package-lock.json') }}
  2. Use Specific Versions

    - uses: actions/checkout@v3  # Good
    - uses: actions/checkout@master  # Avoid
  3. Add Status Badges

    ![Tests](https://github.com/username/repo/actions/workflows/test.yml/badge.svg)
    


Troubleshooting Guide 🔍

Common Issues and Solutions

  1. Workflow Not Running?
    • Check: Is the workflow file in .github/workflows?
    • Check: Is the on: trigger correct?
    • Solution: Validate YAML syntax

  1. Tests Failing in CI but Passing Locally?
    • Check: Node.js version matches
    • Check: All dependencies are in package.json
    • Solution: Use npm ci instead of npm install

  1. Deployment Failed?
    • Check: All required secrets are set
    • Check: Branch permissions
    • Solution: Check deployment logs in Actions tab



Next Steps 🎓

  1. Add These Features:
    • Code coverage reporting
    • Automatic version bumping
    • Slack/Discord notifications
    • Docker image builds

  1. Learn These Concepts:
    • Custom actions
    • Reusable workflows
    • Environment protection rules



Resources 📚




Conclusion 🎉

You now have the knowledge to automate your development workflow with GitHub Actions! Remember:

  1. Start small
  2. Test locally first
  3. Build incrementally
  4. Learn from failures

🎉 Well done on automating your first pipeline! You're on your way to mastering CI/CD. Keep building and automating, and let your pipeline do the heavy lifting! 🎉

Happy automating! 🚀