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

GitHub Actions矩阵中输入参数第二种场景运行失败,求正确写法

解决GitHub Actions动态生成测试类矩阵的问题

你的问题出在手动拼接JSON字符串的方式上,GitHub Actions的表达式解析机制对这种拼接后的字符串处理容易出现语法问题,而且完全没必要这么做。直接用三元运算符结合数组字面量就能解决:

修正后的工作流代码

on:
  workflow_call:
    inputs:
      TEST_CLASS:
        type: string
        required: true

jobs:
  execute-test:
    name: execute-test
    strategy:
      max-parallel: 1
      matrix:
        test_class: ${{ 
          inputs.TEST_CLASS == 'All' 
            ? fromJson('["A", "B", "C"]') 
            : [inputs.TEST_CLASS]
        }}

为什么原来的写法不行?

你之前用'["' + inputs.TEST_CLASS + '"]'手动拼接JSON字符串,这种方式很脆弱:如果输入的测试类名称包含引号、反斜杠等特殊字符,会直接破坏JSON格式,导致fromJson解析失败。而且GitHub Actions支持直接在表达式中使用数组字面量[inputs.TEST_CLASS],完全不需要绕路转成JSON字符串再解析。

更清晰的写法(可选)

如果预定义的测试类列表较长,可以把它放到环境变量里,让代码更易维护:

on:
  workflow_call:
    inputs:
      TEST_CLASS:
        type: string
        required: true

jobs:
  execute-test:
    name: execute-test
    env:
      ALL_TEST_CLASSES: '["A", "B", "C"]'
    strategy:
      max-parallel: 1
      matrix:
        test_class: ${{ 
          inputs.TEST_CLASS == 'All' 
            ? fromJson(env.ALL_TEST_CLASSES) 
            : [inputs.TEST_CLASS]
        }}

内容的提问来源于stack exchange,提问作者Romain D.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 02:52:14