CI/CD Pipeline Setup with GitHub Actions: Automate Your Workflow from Code to Deployment

8.33K 0 0 0 0

✅ Chapter 2: Creating Your First GitHub Actions Workflow

🔍 Introduction

Now that you understand the fundamentals of CI/CD and GitHub Actions, it's time to get hands-on.

In this chapter, you will:

  • Learn the basic structure of a GitHub Actions workflow
  • Create your first real workflow from scratch
  • Understand triggers (events), jobs, steps, and actions
  • Customize workflows for different needs
  • Troubleshoot and monitor your first workflow execution

By the end of this chapter, you’ll have confidence to automate simple build, test, and deployment tasks inside GitHub!


📋 Anatomy of a GitHub Actions Workflow

A GitHub Actions workflow is a YAML file stored inside your repository in:

bash

 

.github/workflows/

🔹 Key Components

Component

Purpose

Workflow

Top-level definition that groups all automation tasks

Event

Trigger that starts the workflow

Job

Collection of steps to perform tasks

Step

Individual command or action

Runner

Machine that runs the jobs (GitHub-hosted or self-hosted)


📜 Basic Structure Example

yaml

 

name: Build and Test

 

on: [push]

 

jobs:

  build:

    runs-on: ubuntu-latest

    steps:

    - name: Checkout code

      uses: actions/checkout@v3

    - name: Install dependencies

      run: npm install

    - name: Run tests

      run: npm test


🚀 Step-by-Step: Creating Your First Workflow

Step 1: Create the Workflow Directory

In your repository:

bash

 

mkdir -p .github/workflows


Step 2: Create a Workflow File

Create a file named ci.yml:

bash

 

touch .github/workflows/ci.yml


Step 3: Write a Simple Workflow

Paste the following content into ci.yml:

yaml

 

name: CI Workflow

 

on:

  push:

    branches:

      - main

 

jobs:

  build:

    runs-on: ubuntu-latest

    steps:

    - name: Checkout repository

      uses: actions/checkout@v3

    - name: Set up Node.js

      uses: actions/setup-node@v3

      with:

        node-version: 16

    - name: Install packages

      run: npm install

    - name: Run unit tests

      run: npm test


Step 4: Push the Workflow

Commit and push the workflow file:

bash

 

git add .

git commit -m "Add CI workflow"

git push origin main


Step 5: Monitor Workflow Execution

Go to your GitHub repository → Click on the Actions tab → See your workflow running live!

You can view:

  • Logs for each step
  • Errors and warnings
  • Status (Success, Failure)

🔔 Understanding Workflow Triggers

Workflows are event-driven.

🔹 Common Events

Event

Description

push

Triggered on code push

pull_request

Triggered when a PR is opened/updated

schedule

Triggered on a cron schedule

workflow_dispatch

Manual trigger via GitHub UI

release

Triggered when a new release is published


📋 Example: Scheduled Workflow

yaml

 

on:

  schedule:

    - cron: '0 0 * * *'  # Every day at midnight UTC


📋 Example: Manual Workflow Dispatch

yaml

 

on:

  workflow_dispatch:

Manually trigger this workflow from GitHub’s UI!


️ Setting up Different Runners

🔹 Default GitHub-hosted Runners

GitHub provides ready-to-use virtual machines:

OS

Label

Ubuntu Linux

ubuntu-latest

Windows

windows-latest

macOS

macos-latest


🔹 Using a Specific Runner

yaml

 

runs-on: ubuntu-latest

OR

yaml

 

runs-on: windows-latest


🧰 Using Pre-built Actions

GitHub Actions has a Marketplace full of reusable Actions.

Popular ones:

Action

Purpose

actions/checkout

Checkout source code

actions/setup-node

Set up Node.js environment

actions/setup-python

Set up Python environment

actions/cache

Cache dependencies

docker/build-push-action

Build and push Docker images


📋 Example: Using a Third-Party Action

yaml

 

- name: Upload Artifact

  uses: actions/upload-artifact@v3

  with:

    name: build-artifact

    path: dist/

Uploads the build folder (dist/) for later use!


🌟 Advanced Customization Basics

Once comfortable, you can:

  • Add multiple jobs (build, test, deploy)
  • Run jobs in parallel or sequentially
  • Use conditionals (if: syntax)
  • Create matrix builds (e.g., Node.js 14/16/18)
  • Use caches to speed up workflows

📋 Example: Running Jobs in Parallel

yaml

 

strategy:

  matrix:

    node: [14, 16, 18]

Tests on Node 14, 16, and 18 simultaneously!


📈 Best Practices for First GitHub Workflows

Best Practice

Why It Matters

Keep workflows simple initially

Easier debugging

Name steps clearly

Easier to trace logs

Use secrets, not hardcoded passwords

Security

Fail fast

Exit early on errors

Modularize workflows as they grow

Maintainability


🚀 Real-World Example: Node.js Build and Deploy Workflow

yaml

 

name: CI/CD

 

on:

  push:

    branches: [main]

 

jobs:

  build:

    runs-on: ubuntu-latest

    steps:

    - uses: actions/checkout@v3

    - uses: actions/setup-node@v3

      with:

        node-version: 16

    - run: npm install

    - run: npm run build

 

  deploy:

    needs: build

    runs-on: ubuntu-latest

    steps:

    - uses: actions/checkout@v3

    - name: Deploy to server

      run: echo "Deploying application..."

Explanation:

  • Build job runs first
  • Deploy job waits for Build to succeed

📚 Common Issues When Starting

Issue

Reason

Fix

Workflow not triggering

Wrong branch or event config

Double-check on: events

Workflow fails immediately

Bad YAML syntax

Validate YAML formatting

Steps fail unexpectedly

Wrong runner environment

Confirm runs-on is correct

Permission denied errors

Secrets not configured

Set GitHub Secrets properly


🚀 Summary: What You Learned in Chapter 2

  • How to create your first GitHub Actions workflow
  • Understanding jobs, steps, runners, and actions
  • Setting triggers: push, pull_request, schedule
  • Using pre-built Actions from Marketplace
  • Best practices to avoid common issues


Congratulations! You've successfully built your first automated workflow with GitHub Actions!

Back

FAQs


❓1. What is GitHub Actions?

Answer: GitHub Actions is a built-in automation tool on GitHub that allows you to build, test, and deploy code directly from your repositories by defining workflows triggered by events like pushes, pull requests, and schedules.

❓2. What are the basic components of a GitHub Actions workflow?

Answer: A GitHub Actions workflow consists of workflows, jobs, steps, and actions:

  • Workflows define the entire pipeline.
  • Jobs are sets of steps that run sequentially or in parallel.
  • Steps are individual tasks like running commands.
  • Actions are pre-built reusable tasks.

❓3. How do I trigger a workflow in GitHub Actions?

Answer: Workflows can be triggered by:

  • Events (e.g., push, pull_request)
  • Scheduled times (cron jobs)
  • Manual triggers (workflow_dispatch)
  • Repository dispatches from external systems

❓4. Can I deploy applications automatically using GitHub Actions?

Answer: Yes! GitHub Actions can automate deployments to servers, Kubernetes clusters, serverless platforms, or cloud providers like AWS, Azure, and GCP after successful builds and tests.

❓5. How do I securely manage secrets like API keys or passwords in GitHub Actions?

Answer: GitHub provides a Secrets management system where sensitive data (like API keys, credentials) can be stored and injected into workflows securely without exposing them in code.

❓6. What types of environments can I run GitHub Actions workflows on?

Answer: GitHub Actions supports runners on:

  • Ubuntu Linux (ubuntu-latest)
  • Windows (windows-latest)
  • macOS (macos-latest) You can also set up self-hosted runners on your own infrastructure.

❓7. What is the benefit of using caching in GitHub Actions workflows?

Answer: Caching (using actions/cache) helps store and reuse dependencies between workflow runs, significantly reducing build times and improving pipeline efficiency.

❓8. How can I create multi-environment CI/CD workflows (e.g., dev, staging, prod)?

Answer: You can create separate jobs or workflows for each environment and control them with conditions (e.g., branch filters like if: github.ref == 'refs/heads/prod') or use manual approvals for deployment jobs.

❓9. Can I run tests across multiple versions of a programming language simultaneously?

Answer: Yes! You can use matrix builds in GitHub Actions to test your application across multiple versions (e.g., Node.js 14, 16, and 18) at the same time, improving compatibility and quality assurance.

❓10. Is GitHub Actions free to use?

Answer: GitHub Actions offers free usage with limits based on your account type:

  • Public repositories: Free unlimited usage
  • Private repositories: Free minutes with limits depending on GitHub plan (Free, Pro, Team, Enterprise); extra usage may incur costs.