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

如何在GitHub Actions中按条件取消当前运行的Workflow?

如何条件性取消当前运行的GitHub Workflow?

问题背景

我想根据特定条件取消当前正在运行的GitHub Workflow,尝试使用一款Cancel Workflow Action,配置如下:

- name: 若目标文件无变更则取消工作流
  if: steps.changed-files.outputs.any_changed != 'true'
  uses: styfle/cancel-workflow-action@0.10.0
  with:
    workflow_id: ${{ github.workflow_id }}
    access_token: ${{ github.token }}

但日志显示该Action仅能取消其他并发运行的Workflow,对当前运行的实例无效:

Found token: yes
Found workflow_id: ["12345567"]
Found 3 runs total.
Found 0 runs to cancel.

想问有没有简便的解决办法,还是必须调用GitHub API?

补充尝试:我试过用gh cli调用API取消当前工作流:

gh api --method POST -H "Accept: application/vnd.github+json" https://api.github.com/repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/cancel

但返回{}后,工作流仍继续执行。


可行解决方案

1. 使用actions/github-script调用API取消当前工作流

styfle的Action确实仅针对并发运行的同工作流实例,要取消当前运行的实例,直接调用GitHub API是可靠方式,推荐用官方的actions/github-script来实现,它内置了认证和上下文:

- name: 取消当前工作流
  if: steps.changed-files.outputs.any_changed != 'true'
  uses: actions/github-script@v6
  with:
    script: |
      await github.rest.actions.cancelWorkflowRun({
        owner: context.repo.owner,
        repo: context.repo.repo,
        run_id: context.runId
      })

调用后,GitHub会将该工作流标记为“已取消”状态,后续步骤会被自动跳过,但当前步骤会执行完成。

2. 为什么之前的gh cli调用无效?

你用gh cli调用后返回{}是正常的——GitHub的取消工作流接口本身就返回空对象。工作流继续执行是因为:调用API后,当前正在运行的步骤会完成,只有还未开始的步骤才会被跳过。如果想让当前job立即停止,可以在调用API后加上退出命令:

gh api --method POST -H "Accept: application/vnd.github+json" https://api.github.com/repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/cancel && exit 0

不过这种方式下,工作流的最终状态会是“成功”而非“已取消”,可根据需求选择。

3. 更轻量的替代:跳过后续步骤而非取消

如果不需要显式标记工作流为“已取消”,可以直接用if条件控制后续所有步骤的执行,或者将核心逻辑放到单独job中,通过job级别的if来跳过整个job:

jobs:
  build:
    runs-on: ubuntu-latest
    if: steps.changed-files.outputs.any_changed == 'true'
    steps:
      # 你的核心构建步骤

这种方式更简洁,避免了API调用的开销。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:01:40