[GitHub Actions] branch conditional

I’d like to make a job or step (either would work for me) conditional in our workflow, and have it validate the current branch is “master”. Is there something we can reference in the if: conditional to match only when the branch being pushed to is master?

6 Likes

You can do a conditional statement using this:

if: github.ref == 'refs/heads/master'
27 Likes

How did you know the value of github.ref? I can’t find it.

https://help.github.com/en/articles/contexts-and-expression-syntax-for-github-actions#github-context

“ref” is a term of art in git (and thus github, it’s a common encounter in the API): https://git-scm.com/book/en/v2/Git-Internals-Git-References

2 Likes

You can print the value to verify:

steps:
    - run: echo ${{github.ref}}
5 Likes

if: github.ref == ‘refs/heads/integration’ && github.event_name == ‘push’ 

You can this command and replace whatever branch or event you want to run for.

To archive the same with multiple branches and for less boilerplate, use the contains function:

    if:
      contains('
        refs/heads/staging
        refs/heads/production
      ', github.ref)

More information: https://stackoverflow.com/a/62419599/2574719

Include this in yout workflow.

# Controls when the action will run. Triggers the workflow on push 
# events but only for the master branch
on:
  push:
    branches: [ master ]