GitHub Actions: run step only for certain pull request base branches

Viewed 6405

I have been working on GitHub Actions from quite some time now, and we have a designated workflow in place. The workflow has been written in yaml.

I am trying to put some if condition for the github.ref and that block of the yaml is being skipped on the run. It means - if the pull request is raised against X branch - that block of code should run.

Something like this:

 
      - name: Branch name check - Running only for DEV branch.. 
        if: ${{contains(github.ref, 'DEV*')}}
        uses: mathrix-education/sonar-scanner@master

        with:
          version: 4.2.0.1873 # required
          typescript: false
          scan: true

Can anyone help me out on this ?

2 Answers

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 }}

Use the following to check for the base of the pull request:

if: ${{contains(github.base_ref, 'DEV')}}

github.ref will contain something like refs/pull/1/merge for pull requests.

Related