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

如何通过GitHub Actions Workflow Call在指定分支运行对应脚本?

解决GitHub Actions指定分支执行对应脚本的问题

问题核心原因

你遇到的问题本质是:调用子工作流时,默认拉取的是仓库默认分支(比如PROD)的deploy_workflow.yml,导致无论传递哪个ref参数,最终执行的都是默认分支里指定的scriptmain.ps1。

最优解决方案:单工作流动态分支判断

不需要为每个分支创建重复工作流,只需在同一个deploy_workflow.yml中根据传入的分支参数动态选择要执行的脚本,步骤如下:

1. 编写通用的deploy_workflow.yml

name: 通用部署工作流

on:
  workflow_call:
    inputs:
      target_ref:
        description: "要部署的目标分支"
        type: string
        required: true

jobs:
  deploy:
    runs-on: windows-latest
    steps:
      - name: 拉取指定分支代码
        uses: actions/checkout@v4
        with:
          ref: ${{ inputs.target_ref }} # 切换到调用方指定的分支

      - name: 确定要执行的脚本路径
        id: get_script
        shell: pwsh
        run: |
          $branch = "${{ inputs.target_ref }}" -replace 'refs/heads/', ''
          switch ($branch) {
            'test' { $script = 'scripttest.ps1' }
            'QA' { $script = 'scriptqa.ps1' }
            'PROD' { $script = 'scriptmain.ps1' }
            default { throw "不支持的分支: $branch" }
          }
          echo "script_path=$script" >> $env:GITHUB_OUTPUT

      - name: 执行部署脚本
        shell: pwsh
        run: |
          .\${{ steps.get_script.outputs.script_path }}

2. 编写触发部署的父工作流(repository_dispatch触发)

name: 触发部署

on:
  repository_dispatch:
    types: [deploy_trigger]

jobs:
  trigger_deploy_job:
    runs-on: ubuntu-latest
    steps:
      - name: 调用通用部署工作流
        uses: actions/github-script@v7
        with:
          script: |
            await github.rest.actions.createWorkflowDispatch({
              owner: context.repo.owner,
              repo: context.repo.repo,
              workflow_id: 'deploy_workflow.yml',
              ref: context.payload.ref,
              inputs: {
                target_ref: context.payload.ref
              }
            })

关键说明

  • checkout步骤必须指定ref: ${{ inputs.target_ref }},确保拉取的是目标分支的代码和脚本文件。
  • 通过switch语句(PowerShell语法)根据分支名动态映射脚本路径,避免硬编码冗余。
  • 如果调用方传递的ref格式是refs/heads/test,用-replace 'refs/heads/', ''提取纯分支名,判断更简洁。

内容的提问来源于stack exchange,提问作者samauces

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 15:31:05