DevopsIntermediate

How to Set Up a CI/CD Pipeline with GitHub Actions

Admin
9 min read

TL;DR

Learn how to automate your software development workflow using GitHub Actions for continuous integration and deployment.

Executive Summary

GitHub Actions runs your build, test, and deployment automation in YAML workflows stored with the code, triggered by events in the repository. This guide covers the core model — workflows, jobs, steps, actions, and runners — then builds a complete CI/CD pipeline: checkout, setup, test, build, and deployment through protected environments. It also covers the practices that separate a toy pipeline from a production one: dependency caching, matrix builds, reusable workflows, least-privilege tokens, and secret handling. After reading it, you will be able to design a pipeline that is fast enough to run on every pull request and controlled enough to deploy to production.

One workflow file, many parallel jobs An event starts the workflow; jobs run in parallel until needs turns them into a pipeline. Trigger push · PR · schedule Workflow YAML in repo Jobs parallel by default Steps shell or action Runner hosted / self-hosted Artifact built once, scanned Environment approval + secrets Deploy promote, never rebuild The artifact deployed is the artifact built and scanned in CI — never rebuild at deploy time. Jobs declare dependencies with needs; environments are where approval, secrets, and branch rules live.

Why This Matters

The pipeline is where your delivery promises are kept or broken. A slow pipeline trains developers to batch changes and skip runs, which concentrates risk into exactly the large, infrequent deployments that fail. A pipeline without environment controls lets any merged pull request reach production with no checkpoint, and a pipeline with over-privileged tokens turns a compromised dependency or a careless workflow edit into a supply-chain incident — the workflow file is code that runs with access to your secrets and your cloud credentials. Conversely, a fast, well-structured pipeline is the enabling constraint for everything else in modern delivery: small changes, frequent deploys, and confident rollbacks.

Core Concepts

The Execution Model

Four terms organise everything in GitHub Actions:

ConceptDescriptionPurpose
WorkflowAn automated process defined in a YAML file under .github/workflowsDefines the CI/CD steps for an event
JobA set of steps running on one runner; jobs run in parallel by defaultGroups related work such as build, test, deploy
StepA single task: a shell command or an actionThe unit of execution inside a job
ActionA reusable unit of work, published in the Marketplace or your own repoCheckout, runtime setup, deployment, scanning
RunnerThe machine executing jobs — GitHub-hosted or self-hostedProvides the execution environment

Workflows trigger on events: pushes, pull requests, tags, schedules, manual dispatch, and more. Jobs declare dependencies with needs, which is how you turn parallel jobs into a pipeline with an order.

The GitHub Actions stack — five layers, one control point each Events — push, pull request, schedule, manual dispatch Workflow — one YAML file per automation, stored with the code Jobs — parallel by default; needs declares the order Steps & actions — shell commands or Marketplace actions, pinned to a SHA Runners & environments — hosted or self-hosted; approvals, secrets, OIDC YAML is the interface; the runner is the machine; the environment is the control point. Every layer above the runner is code in the repo — review workflow files like production code.

A Working CI Workflow

This is the skeleton almost every project starts from — install, test, and build on pushes and pull requests to main:

name: CI/CD Pipeline

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

jobs:
  build:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v4
    - name: Set up Node.js
      uses: actions/setup-node@v4
      with:
        node-version: '22'
        cache: 'npm'
    - name: Install dependencies
      run: npm ci
    - name: Run tests
      run: npm test
    - name: Build
      run: npm run build

Two upgrades turn this into a serious pipeline. First, install with the lockfile-respecting command for your ecosystem (npm ci for Node) so builds are reproducible. Second, cache dependencies — the setup actions for most languages can cache package stores keyed on the lockfile, which is usually the single largest time saving available. Keep the whole pull-request pipeline fast; a workflow that takes forty minutes will be routed around.

Testing Strategy in the Pipeline

Order tests by speed and signal. Unit tests run first and gate everything. Integration tests that need services can run in a parallel job using service containers. End-to-end tests are the slowest and flakiest tier, so run the critical paths on pull requests and the full suite on a schedule or before deployment. Security scanning belongs in the same workflow family: code scanning (CodeQL for supported languages), dependency review, and container image scanning before any image is promoted.

Test typePurposeTypical tools
Unit testsValidate individual units of codeJest, Mocha, pytest, JUnit
Integration testsVerify components work togetherTestcontainers, Supertest, pytest with a real database
End-to-end testsDrive the whole application as a user wouldPlaywright, Cypress, Selenium
Security testsFind vulnerabilities in code and dependenciesCodeQL, Snyk, Trivy

Environments, Secrets, and Deployment

GitHub environments are the control point for deployment. An environment holds its own secrets and variables, and can require human approval, restrict which branches may deploy to it, and enforce a wait timer. A production job that declares environment: production pauses for a required reviewer instead of deploying the moment tests pass. Secrets are masked in logs and withheld from workflows triggered by forks — never echo them, and prefer short-lived cloud credentials via OIDC federation over stored static keys: the workflow exchanges its identity token for temporary cloud credentials, so there is no long-lived secret to leak.

Deployment itself should promote the artifact built in CI, never rebuild at deploy time. Choose the rollout strategy to match the risk:

StrategyDescriptionUse case
RollingReplace instances graduallyDefault for stateless services; zero downtime
Blue-greenRun two full environments, switch trafficFast, clean rollback by switching back
CanaryRelease to a small share of traffic firstHigh-risk changes where real-traffic validation matters

Permissions and Supply-Chain Hygiene

The GITHUB_TOKEN should be scoped per workflow and per job with the permissions key, defaulting to read-only repository contents and adding write scopes only where a job genuinely needs them. Pin third-party actions to a full commit SHA rather than a mutable tag — a tag can be moved by whoever controls the action's repository, and your workflow will run the new code with your token. Review what an action does before adopting it, the same as any dependency.

Reuse: Matrix, Reusable Workflows, Composite Actions

Three mechanisms keep a growing workflow estate manageable. Matrix builds run one job definition across combinations of operating systems and runtime versions. Reusable workflows (workflow_call) let one workflow invoke another, so ten repositories can share one organisation-standard pipeline. Composite actions package a sequence of steps into a single action. Use them in that order of preference: matrices for variation, reusable workflows for whole pipelines, composite actions for step sequences.

Decision Framework

What shape is the automation? Start with one honest workflow — add the control that matches the risk, not the fashion. How many repos and services? one repo · monorepo · many repos One service, one repo single workflow Monorepo, several services path filters Many repos, one standard reusable workflows GPUs / private network self-hosted runners A workflow that takes forty minutes will be routed around — speed is a feature, not a nicety.

SituationRecommendation
Small project, one serviceOne workflow: test on pull request, deploy from main through a protected environment
Monorepo with several servicesPath filters so each service's workflow runs only when its files change
Many repositories, one standardCentral reusable workflows, versioned and consumed by SHA or tag
Slow test suiteSplit jobs by test tier, cache dependencies, parallelise; quarantine flaky tests instead of retrying blindly
Regulated production environmentEnvironment with required reviewers, branch restrictions, OIDC cloud credentials, read-only default token
Builds need GPUs or internal network accessSelf-hosted runners, isolated from pull requests from forks
Third-party action neededPin to commit SHA, review source, prefer actions from verified creators

Implementation Checklist

  • [ ] Workflows live in .github/workflows and are reviewed like production code
  • [ ] Pull request pipeline completes fast enough that developers never consider skipping it
  • [ ] Dependencies install from the lockfile and are cached between runs
  • [ ] permissions is set explicitly; the default token is read-only
  • [ ] Production deployment goes through an environment with required approval
  • [ ] Cloud access uses OIDC short-lived credentials, not stored static keys
  • [ ] Third-party actions are pinned to commit SHAs
  • [ ] The artifact deployed is the artifact built and scanned in CI
  • [ ] A rollback path (redeploy previous version) is documented and has been executed at least once
  • [ ] Failed workflow notifications reach a channel a human actually reads
  • Trade-offs

    GitHub Actions trades control for convenience. GitHub-hosted runners are ephemeral and easy, but you accept their environment, their queue, and per-minute economics at scale — heavy build estates often end up on self-hosted runners and inherit the maintenance and security burden that hosting was supposed to remove. YAML pipelines are readable but weak as a programming language: complex logic gets pushed into shell scripts and reusable workflows to escape YAML's limits. Vendor coupling is real too — workflows, environments, and the Marketplace ecosystem do not port to another CI system without a rewrite. Finally, the ease of adding a Marketplace action is a supply-chain decision made casually; every action is code from a third party running inside your trust boundary.

    When Not to Use

    GitHub Actions is the natural choice for code already on GitHub, but it is not universal. If your code lives on another platform, its native CI (GitLab CI, Bitbucket Pipelines) avoids a split-brain setup. If you need long-running jobs, exotic hardware, or builds inside a restricted network with strict data controls, a self-managed system such as Jenkins or Buildkite gives you control Actions cannot. And if your organisation already runs a standardised CI platform with support and compliance sign-off, adopting Actions per-team creates a second platform to secure and audit — consistency with the estate usually wins over individual preference.

    Conclusion

    Start with one honest workflow: install from the lockfile, run the tests, build once. Then add the controls that make it production-grade — caching for speed, environments for approval, OIDC for credentials, pinned actions and a read-only token for safety. A GitHub Actions pipeline built in that order stays fast enough to be used and strict enough to be trusted.

    References

  • GitHub Actions Documentation
  • GitHub Actions Marketplace
  • GitHub Actions Community
  • Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.