How to trigger workflows conditionally?

· Category: DevOps & CI/CD

Short answer

Use conditional logic with if expressions and path filters to run GitHub Actions workflows or steps only under specific conditions.

Steps

  1. Use on.push.paths to filter by changed files.
  2. Use if at the job or step level.
  3. Reference event payload data in conditions.

Example

on:
  push:
    paths:
      - 'src/**'
      - 'tests/**'

jobs:
  deploy:
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - run: ./deploy.sh

Step-level condition:

steps:
  - name: Notify
    if: failure()
    run: echo "Build failed"

Tips

  • Use if: github.event_name == 'pull_request' for PR-only steps.
  • Combine conditions with && and ||.
  • Use paths-ignore to skip workflows for documentation changes.

Common issues

  • if expressions must be valid GitHub Actions syntax.
  • Path filters do not work for workflow_dispatch events.
  • Conditions are evaluated as strings; 0 is truthy.