AI Hints
Home›CI/CD with GitHub Actions Tutorial›Conditions and Matrices
CI/CD with GitHub Actions · Lesson 46 of 138

Conditions with if

Run only when.

⏱ 2 min read▶ Video at 52:27🎓 Free
Watch this lesson in the CI/CD with GitHub Actions courseWatch on YouTube ↗Full CI/CD with GitHub Actions course

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.

Conditions with if
From the video: Conditions with if
  • Not every step, every time
  • Deploy only from main
  • The if key

Three conditions

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: Conditions
on: [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"

Three runs

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

Summary

If decides whether a step or job runs. Combine checks with and, or, and not. Next, conditions that look at what already happened.

Key takeaways
  • if: github.ref_name == 'main'
  • && || !
  • No braces needed
Next up: Status Functions — success, failure, always