Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I avoid running a Github Actions Job on a pull-request

I have a GitHub action workflow that tests, builds and deploys. Quite common.

I want the job test to run on both main and PRs (into main). But I want the build and deploy to only run on pushes to main. How can I safely protect this?

The summarized .github/workflows/ci.yml looks like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

name: CI

on:
  push:
    branches: ["main"]
  pull_request:
    branches: ["main"]

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - name: "Lint, Test and Report"
        run: echo "running linter, then tests then report on this"
 
  build:
    needs: test
    runs-on: ubuntu-latest

    steps:
      - name: "Build"
        run: echo "Building the artifacts"

  deploy:
    needs:
      - test
      - build
    runs-on: ubuntu-latest

    steps:
      - name: "Deploy to Production"
        run: echo "Drumroll...."

I don’t see any ENV variable or github.x attribute that indicates that this is a PR. Maybe I’m missing something obvious?

Is it safe to match on branch-name instead? And e.g. use a

    if: startsWith(github.ref, 'refs/heads/main')

to ensure we only ever run when the branch is main?

>Solution :

Yes, this is safe. However, change it to:

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

because otherwise somebody could push a branch mainfoo and you’d trigger the job as well.

An alternative would be to check for the event name, like:

if: github.event.name == 'push'

however I’d say this is less robust, since somebody could change the trigger above and remove the branches: .. part of the push trigger and suddenly you’re deploying from PRs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading