如何让Github Actions仅在特定分支向master发起PR时运行?
skip-* Branches to Master Let's break down what went wrong with your original configuration and fix it step by step.
The Problem with Your Current Setup
Your existing branches field in the on: pull_request section specifies target branches—meaning the workflow triggers whenever a PR is opened to master or any skip-* branch. That's why it's running for all PRs to master, regardless of which branch the PR comes from.
Solution 1: Filter at the Job Level (Flexible)
This approach first triggers the workflow for all PRs to master, then filters out any PRs that don't come from a skip-* branch before running the job:
name: Auto Approve Pull Request on: pull_request: branches: - 'master' # Only trigger for PRs targeting master jobs: build: name: Approve PR runs-on: ubuntu-latest # Only run this job if the source branch starts with "skip-" if: startsWith(github.head_ref, 'skip-') steps: - name: Fetch our code uses: username/my-github-repo@master with: # Use a GitHub Secret instead of hardcoding your token! token: ${{ secrets.GITHUB_TOKEN }} env: BRANCH_PREFIX: "skip-" PULL_REQUEST_TARGET_BRANCH: "master"
Solution 2: Filter at the Event Level (More Efficient)
If you want to avoid triggering the workflow entirely for non-matching PRs, use head_refs to specify allowed source branches alongside the target master branch:
name: Auto Approve Pull Request on: pull_request: branches: - 'master' # Target branch is master head_refs: - 'skip-*' # Only allow source branches matching skip-* jobs: build: name: Approve PR runs-on: ubuntu-latest steps: - name: Fetch our code uses: username/my-github-repo@master with: token: ${{ secrets.GITHUB_TOKEN }} env: BRANCH_PREFIX: "skip-" PULL_REQUEST_TARGET_BRANCH: "master"
Key Notes:
- Avoid hardcoding tokens: Always use GitHub Secrets (like
${{ secrets.GITHUB_TOKEN }}or a custom secret) to keep your credentials secure. github.head_ref: This variable holds the name of the source branch that the PR is coming from—perfect for filtering which PRs run your job.
内容的提问来源于stack exchange,提问作者Njeri Ngigi

