PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 9, 2022

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

 October 09, 2022     continuous-integration, github-actions     No comments   

Issue

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:

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.



Answered By - rethab
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing