Not every step should run every time. Deploy only from main. Comment only on pull requests. Run the slow tests only on release branches. The if key decides, using an expression.
The first condition compares the branch with main. The second checks the event. The third combines two checks with two ampersands, meaning and. Both must be true. There's also two bars for or, and an exclamation mark for not. In if, you can leave out the double curly braces.
.github/workflows/conditions.ymlyaml
name: Conditionson: [push, pull_request]jobs: checks: runs-on: ubuntu-latest steps: - run: pytest -q - name: Only on main if: github.ref_name == 'main' run: echo "On main" - name: Only for pull requests if: github.event_name == 'pull_request' run: echo "Reviewing a PR" - name: Release branches if: startsWith(github.ref_name, 'release/') && github.event_name == 'push' run: echo "Release push"
On main, only the main step runs. As a pull request, only the pull request step runs. And as a push to a release branch, the release step runs. Same file, three different behaviours, decided by the conditions.
Terminal
run-steps .github/workflows/conditions.yml | grep -E "^ [-✓]" ✓ Run pytest -q ✓ Only on main - Only for pull requests (skipped) - Release branches (skipped)run-steps .github/workflows/conditions.yml --event pull_request --ref fix | grep -E "^ [-✓]" ✓ Run pytest -q - Only on main (skipped) ✓ Only for pull requests - Release branches (skipped)run-steps .github/workflows/conditions.yml --ref release/2.0 | grep -E "^ [-✓]" ✓ Run pytest -q - Only on main (skipped) - Only for pull requests (skipped) ✓ Release branches