We ran into a similar thing when constructing a github workflow. The conditions we are working under:
- We want step 1 to only run on pushes OR pull requests to develop.
- We want step 2 to only run on pull requests to master.
- Steps must be in a single workflow.yaml.
After some research, below is what we came up with. I found Github Actions to be very flexible, with a lot of options that Gitlab and Bitbucket don't have. But that is also the downside and makes it more complex to understand sometimes.
---
name: my-workflow
on:
push:
branches:
- develop
pull_request:
branches:
- develop
- main
types:
- closed
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: checkout repo
uses: actions/checkout@v1
- name: step 1
if: github.ref == 'refs/heads/develop' || github.event.pull_request.base.ref == 'develop'
run: echo "Hello develop"
- name: step 2
if: github.event.pull_request.base.ref == 'master'
run: echo "Hello master"
I would recommend not using if-statements on branches too often. This introduces inconsistencies between the deployments of different branches. For some use cases you may be better of using github environments (Enterprise only). For example, if you need to set different environment variables or secrets for different branches. Below is a simple example where you could have two github environments (develop and main) both containing different values for the secret MY_SECRET.
name: my-workflow
on:
push:
branches:
- develop
- main
jobs:
deploy:
runs-on: ubuntu-latest
name: Do something
steps:
- run: echo "Example using environments corresponding branch names"
environment: ${{ github.ref == 'refs/heads/main' && 'main' || github.ref == 'refs/heads/develop' && 'develop' }}
env:
MY_SECRET: ${{ secrets.MY_SECRET }}