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

如何在GitHub Actions可重用工作流中实现动态if条件?

解决GitHub Actions可重用工作流动态if条件问题

你的问题根源在于:直接使用${{ inputs.if_condition }}时,输入的条件字符串会被当作字面量非空字符串处理(而非GitHub Actions表达式),因此无论条件内容是什么,都会被判定为true,导致步骤始终执行。

解决方案:嵌套表达式解析

通过嵌套${{ }}让GitHub Actions将输入的字符串解析为合法表达式:

  1. 保持输入变量定义不变:
if_condition:
  description: "Condition to determine if 'Build and Push image' step should execute"
  required: false
  type: string
  default: 'true'  # 默认执行步骤
  1. 修改步骤的if条件为嵌套表达式:
- name: Build and Push image
  if: ${{ ${{ inputs.if_condition }} }}
  id: build-image
  uses: docker/build-push-action@v6

原理说明

当用户传入github.ref == 'refs/heads/main'这类条件时,内层${{ inputs.if_condition }}会替换为该字符串,外层${{ }}会自动解析这个字符串为GitHub Actions表达式,从而正确判断分支是否符合要求。默认值'true'会被解析为布尔值true,确保步骤在无输入条件时自动执行。

替代实现方式

也可以通过format+fromJson函数实现相同效果,语法更清晰:

- name: Build and Push image
  if: ${{ fromJson(format('{{ {0} }}', inputs.if_condition)) }}
  id: build-image
  uses: docker/build-push-action@v6

注意事项

用户传入的条件必须是合法的GitHub Actions表达式,比如:

  • 分支判断:github.ref == 'refs/heads/main'
  • 状态判断:success()、always()
  • 多条件组合:github.ref == 'refs/heads/main' && github.event_name == 'push'

内容的提问来源于stack exchange,提问作者vin'm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 05:33:10