You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Github Actions仅在特定分支向master发起PR时运行?

Fix: Trigger GitHub Actions Only for PRs from 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 07:37:27