How to write a GitHub Actions workflow?

· Category: DevOps & CI/CD

Short answer

A GitHub Actions workflow is a YAML file stored in .github/workflows/. It defines events that trigger the workflow, jobs that run on runners, and steps that execute commands or actions.

Steps

  1. Create a file in .github/workflows/.
  2. Define the on trigger.
  3. Define jobs with runs-on.
  4. Add steps with run or uses.

Example

name: Build and Test
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: '18'
      - name: Install
        run: npm ci
      - name: Test
        run: npm test

Tips

  • Use needs to create job dependencies.
  • Use env for environment variables.
  • Use if for conditional steps.

Common issues

  • Indentation errors in YAML cause workflow parsing failures.
  • Missing actions/checkout means the workspace is empty.
  • Secrets must be referenced with ${{ secrets.NAME }}.