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 - Gilberto Lyons (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.