如何在GitHub Actions中调用工作流并实现触发即遗忘
GitHub Actions 触发即遗忘式外部工作流调用示例
要实现主工作流触发外部工作流后立即继续执行、不等待外部工作流完成的效果,核心是通过GitHub API触发外部工作流的workflow_dispatch事件,而非使用workflow_call(后者会强制主工作流等待)。以下是两种可行的实现方案:
示例1:使用curl直接调用GitHub API
主工作流(.github/workflows/main.yml)
name: 主工作流 on: [push] jobs: trigger-external-workflow: runs-on: ubuntu-latest steps: - name: 触发外部工作流(触发即遗忘) run: | curl -X POST \ -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ -H "Accept: application/vnd.github.v3+json" \ https://api.github.com/repos/${{ github.repository_owner }}/${{ github.event.repository.name }}/actions/workflows/external.yml/dispatches \ -d '{"ref":"main", "inputs": {"param1": "测试参数1", "param2": "测试参数2"}}' continue-on-error: true # 可选:避免API调用失败阻塞主流程 main-next-task: runs-on: ubuntu-latest needs: trigger-external-workflow # 仅等待触发请求发送完成,而非外部工作流执行完毕 steps: - name: 执行主工作流后续任务 run: | echo "主工作流已触发外部工作流,现在继续执行自身任务" echo "无需等待外部工作流的执行结果"
被调用的外部工作流(.github/workflows/external.yml)
name: 外部工作流 on: workflow_dispatch: inputs: param1: description: '传入参数1' required: true param2: description: '传入参数2' required: true jobs: external-processing: runs-on: ubuntu-latest steps: - name: 执行外部工作流任务 run: | echo "外部工作流启动,参数1: ${{ github.event.inputs.param1 }}" echo "执行耗时任务模拟..." sleep 30 # 模拟长时间运行的任务 echo "外部工作流执行完成"
示例2:使用官方actions/github-script动作
该方案更简洁,无需手动编写curl命令,由官方动作处理API调用细节。
主工作流(.github/workflows/main.yml)
name: 主工作流 on: [push] jobs: trigger-external: runs-on: ubuntu-latest steps: - name: 触发外部工作流(触发即遗忘) uses: actions/github-script@v6 with: script: | await github.rest.actions.createWorkflowDispatch({ owner: context.repo.owner, repo: context.repo.repo, workflow_id: 'external.yml', ref: 'main', inputs: { param1: '来自主工作流的参数', param2: '另一个测试参数' } }) continue-on-error: true # 可选:容错处理 main-continue-task: runs-on: ubuntu-latest needs: trigger-external steps: - name: 主工作流后续任务 run: | echo "主工作流继续执行,完全不依赖外部工作流的状态" echo "外部工作流将在后台独立运行"
被调用的外部工作流(.github/workflows/external.yml)
name: 外部工作流 on: workflow_dispatch: inputs: param1: description: '传入参数1' required: true param2: description: '传入参数2' required: true jobs: external-job: runs-on: ubuntu-latest steps: - name: 执行外部工作流任务 run: | echo "外部工作流启动,参数1: ${{ github.event.inputs.param1 }}" echo "执行耗时操作..." sleep 60 # 模拟更长时间任务 echo "外部工作流执行完毕"
关键说明
- 上述方案均通过
workflow_dispatch事件触发外部工作流,主工作流仅负责发送触发请求,发送完成后立即结束对应任务,不会等待外部工作流执行。 - 默认的
GITHUB_TOKEN已具备触发同仓库工作流的权限;若外部工作流在其他仓库,需使用拥有目标仓库workflow权限的个人访问令牌(PAT)替换GITHUB_TOKEN,并修改API请求中的仓库信息。 continue-on-error: true为可选配置,用于避免触发请求失败时阻塞主工作流的后续任务。
内容的提问来源于stack exchange,提问作者user2731883
相关产品推荐
相关产品推荐

