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

如何在GitHub复合工作流中实现基于条件的输入变量定义

实现复合Action的条件必填输入变量

GitHub Actions的输入变量(inputs)本身不支持直接基于其他输入值设置动态必填规则,我们可以通过在复合Action中添加前置校验步骤来实现你的需求,具体操作如下:

1. 修改action.yml配置并添加校验逻辑

先将environment的required设为false,再通过新增的校验步骤来实现条件必填的逻辑,同时修正原有步骤的条件写法:

---
name: executeCO

inputs:
  environment:
    required: false  # 先设为非必填,后续通过校验控制
    type: string
  action:
    required: true
    default: "create"
    type: string
  SNpass:
    required: true

runs:
  using: "composite"
  steps:
    # 前置校验:当action不是close时,强制检查environment是否已传入
    - name: Check environment requirement
      shell: powershell
      run: |
        if ('${{ inputs.action }}' -ne 'close' -and '${{ inputs.environment }}' -eq '') {
          Write-Error "environment is required when action is not 'close'"
          exit 1
        }
      if: ${{ always() }}  # 确保校验在所有情况下优先执行

    # 修正Create CO步骤的条件判断(需将if放在step层级而非脚本内)
    - name: Create CO
      run: |
        Set-Location "${{ github.workspace }}\betech\Scripts"         
        $SNpass="${{ inputs.SNpass }}"
        Write-Host ./CreateCO.ps1 -myenv "${{ inputs.environment }}" -SNpass $SNpass
      shell: powershell
      if: ${{ inputs.action == 'create' }}

    # 修正Close CO步骤的条件判断
    - name: Close CO
      run: |
        Set-Location "${{ github.workspace }}\betech\Scripts"         
        $SNpass="${{ inputs.SNpass }}"
        Write-Host ./CloseCO.ps1 -myenv "${{ inputs.environment }}" -SNpass $SNpass
      shell: powershell
      if: ${{ inputs.action == 'close' }}

关键细节说明

  • 校验逻辑:通过PowerShell脚本判断,当action不等于close时,如果environment为空则直接抛出错误并终止流程,以此实现"非close场景下environment必填"的要求
  • 步骤条件修正:原来把if写在脚本内部只会控制脚本内的代码片段,无法跳过整个步骤;将if放在step层级,才能真正跳过不需要执行的步骤
  • 调用适配:调用该Action时,若传入action: 'close'可省略environment参数;若action为其他值(如create),则必须传入environment,否则会触发校验错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 12:53:23