'Github actions How to only run a step when merging into master

I have been trying to get this right for hours, and nothing I have managed to find has helped. I am trying to setup a github action that will run tests on every pull request into master and any changes to the master branch, but only run the deploy step when there are changes to the master branch.

Here is a simple reproduction of what I am trying to do.

name: Main
on:
  push:
    branches:
      - "main"
  pull_request:
    branches:
      - "main"
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Test
        run: echo "running tests"
      - name: Deploy
        run: echo "Deploying"
        if: github.head_ref == 'main'

I have tried multiple conditionals I have found here / on other forums, I have tried moving the if statement above and below run I am completely out of ideas. Everything I have tried either runs the deploy step on both pull request and merge or skips the deploy step on both pull request and merge.



Solution 1:[1]

Just use:

github.ref == 'refs/heads/master'

or:

github.ref == 'refs/heads/main'

Depending on which branch you want to check

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1