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

如何通过键值对简化GitHub Workflow输入选项并在矩阵中使用?

GitHub Workflow简化输入选项报错的解决方案

问题背景

原本的Workflow配置可正常运行,但workflow_dispatch的输入选项是冗长的服务器ID字符串,在GitHub页面上难以阅读。尝试用env定义键值对替换为ALL/ALL2的简洁选项后,出现报错:

The workflow is not valid. Unrecognized named-value: 'env' within expression: fromJSON(format('[{0}]', env[inputs.package]))

核心原因:strategy.matrix在job初始化前解析,此时workflow级别的env还未加载,无法在matrix表达式中引用。

可行解决方案

方案一:硬编码映射表达式

直接在matrix中根据输入选项返回对应服务器数组,无需依赖env,保持输入简洁的同时解决解析问题:

name: test

on: 
  workflow_dispatch:
    inputs:
      package:
        description: The server where you wish to deploy & test your code.
        required: true
        type: choice
        options:
          - ALL
          - ALL2

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        package: ${{ 
          inputs.package == 'ALL' 
            ? fromJSON('["i-xxxxxxxxxxxxxxxxx","2-xxxxxxxxxxxxxxxxx","3-xxxxxxxxxxxxxxxxx"]')
            : fromJSON('["i-xxxxxxxxxxxxxxxxx","2-xxxxxxxxxxxxxxxxx","5-xxxxxxxxxxxxxxxxx"]')
        }}
    steps:
      # 替换为你的实际步骤
      - name: Print target server
        run: echo "Testing server: ${{ matrix.package }}"

方案二:使用仓库变量(推荐,便于维护)

将服务器列表存储为仓库变量,实现配置与代码分离,后续修改无需改动Workflow文件:

  1. 在仓库的Settings > Secrets and variables > Variables中添加两个变量:

    • ALL_SERVERS:值填写["i-xxxxxxxxxxxxxxxxx","2-xxxxxxxxxxxxxxxxx","3-xxxxxxxxxxxxxxxxx"]
    • ALL2_SERVERS:值填写["i-xxxxxxxxxxxxxxxxx","2-xxxxxxxxxxxxxxxxx","5-xxxxxxxxxxxxxxxxx"]
  2. 修改Workflow配置:

name: test

on: 
  workflow_dispatch:
    inputs:
      package:
        description: The server where you wish to deploy & test your code.
        required: true
        type: choice
        options:
          - ALL
          - ALL2

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        package: ${{ 
          inputs.package == 'ALL' 
            ? fromJSON(vars.ALL_SERVERS)
            : fromJSON(vars.ALL2_SERVERS)
        }}
    steps:
      # 替换为你的实际步骤
      - name: Print target server
        run: echo "Testing server: ${{ matrix.package }}"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 10:53:15