如何通过键值对简化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文件:
在仓库的
Settings > Secrets and variables > Variables中添加两个变量:ALL_SERVERS:值填写["i-xxxxxxxxxxxxxxxxx","2-xxxxxxxxxxxxxxxxx","3-xxxxxxxxxxxxxxxxx"]ALL2_SERVERS:值填写["i-xxxxxxxxxxxxxxxxx","2-xxxxxxxxxxxxxxxxx","5-xxxxxxxxxxxxxxxxx"]
修改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
相关产品推荐
相关产品推荐

