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
- Create a file in
.github/workflows/. - Define the
ontrigger. - Define jobs with
runs-on. - Add steps with
runoruses.
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
needsto create job dependencies. - Use
envfor environment variables. - Use
iffor conditional steps.
Common issues
- Indentation errors in YAML cause workflow parsing failures.
- Missing
actions/checkoutmeans the workspace is empty. - Secrets must be referenced with
${{ secrets.NAME }}.