如何配置GitHub Actions仅在指定push option推送时触发
实现方法
GitHub Actions 原生的 push 触发事件没有提供直接筛选 push option 的配置字段,你最初写的 push.option 属于不存在的配置项,无法生效,正确的实现方式是通过事件上下文的条件判断做拦截,具体配置如下:
基础可用配置
首先正常配置 push 事件作为触发源,再通过 if 字段判断本次 push 携带的参数列表里是否包含目标值:
name: Trigger on release option on: push: # 可按需指定监听的分支,避免全分支触发浪费运行额度 branches: [main] # 工作流级判断:不满足条件直接终止整个工作流,不会运行任何job if: contains(github.event.push_options, 'release') jobs: release: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 # 后续自定义的构建、发布等步骤在此处添加即可
效果验证
- 执行
git push --push-option=release(或简写git push -o release)推送代码时,github.event.push_options数组会包含release字符串,判断条件成立,工作流正常运行 - 执行
git push --push-option=foo或不带任何 push option 推送时,判断条件不成立,工作流会直接跳过,不会执行后续任务
进阶用法
如果需要根据不同的 push option 触发不同的任务,可以不给工作流加全局判断,改为在单个 job 维度配置判断规则,示例:
name: Multi-option trigger on: push jobs: run-test: runs-on: ubuntu-latest if: contains(github.event.push_options, 'debug') steps: - run: echo "运行调试测试任务" run-release: runs-on: ubuntu-latest if: contains(github.event.push_options, 'release') steps: - run: echo "运行正式发布任务"
注意事项
- 本地 Git 版本需要在 2.10 及以上,才支持
--push-option参数 - 不要在
on.push配置下写不存在的option字段,会被GitHub识别为无效配置,导致工作流运行异常
内容的提问来源于stack exchange,提问作者tcpiper
相关产品推荐
相关产品推荐

