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
- Use
on.push.pathsto filter by changed files. - Use
ifat the job or step level. - 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-ignoreto skip workflows for documentation changes.
Common issues
ifexpressions must be valid GitHub Actions syntax.- Path filters do not work for workflow_dispatch events.
- Conditions are evaluated as strings;
0is truthy.