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

如何在GitHub YAML工作流中设置带默认值的可手动输入变量

GitHub Actions工作流:同时支持手动指定变量与自动触发默认值

问题核心:当工作流由push事件触发时,workflow_dispatch定义的inputs变量不存在,直接引用会返回null,导致相关步骤逻辑失效。以下是两种可行的解决方式:

方案1:在变量引用处直接添加兜底默认值

直接在使用变量的if条件中,通过||运算符设置默认值,确保自动触发时变量有值:

name: Example
on:
  workflow_dispatch:
    inputs:
       runTests:
         description: 运行测试
         required: true
         default: true
         type: Boolean
       uploadArtifacts:
         description: 上传构建产物
         required: true
         default: false
         type: Boolean
  push:
    branches:
    - master
    - main 
    - release/*

jobs:
  Build_Job:
    runs-on: [self-hosted, raya]
    steps:
    - name: 运行测试
      if: ${{ inputs.runTests || true }}
      run: echo "执行测试任务..."

    - name: 发布构建产物
      if: ${{ inputs.uploadArtifacts || false }} 
      uses: actions/upload-artifact@v2
      with:
        name: Installer
        path: "${{ runner.temp }}/AppxPackages/"

方案2:通过环境变量统一管理默认值

将变量统一注入到job的环境变量中,后续步骤直接引用环境变量,更适合变量需要多处复用的场景:

name: Example
on:
  workflow_dispatch:
    inputs:
       runTests:
         description: 运行测试
         required: true
         default: true
         type: Boolean
       uploadArtifacts:
         description: 上传构建产物
         required: true
         default: false
         type: Boolean
  push:
    branches:
    - master
    - main 
    - release/*

jobs:
  Build_Job:
    runs-on: [self-hosted, raya]
    env:
      # 手动触发时取inputs值,自动触发时用默认值
      RUN_TESTS: ${{ inputs.runTests || 'true' }}
      UPLOAD_ARTIFACTS: ${{ inputs.uploadArtifacts || 'false' }}
    steps:
    - name: 运行测试
      if: ${{ env.RUN_TESTS == 'true' }}
      run: echo "执行测试任务..."

    - name: 发布构建产物
      if: ${{ env.UPLOAD_ARTIFACTS == 'true' }} 
      uses: actions/upload-artifact@v2
      with:
        name: Installer
        path: "${{ runner.temp }}/AppxPackages/"

注意事项

  • 布尔类型变量在自动触发时为undefined,使用||运算符时,要确保兜底值与workflow_dispatch的默认值一致;
  • 方案2中环境变量存储的是字符串类型,所以判断时要用== 'true'而非直接判断布尔值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:54:26