GitHub Actions中如何将ls命令输出转为策略矩阵有效输入?
解决GitHub Actions中ls输出转策略矩阵的报错问题
问题场景
需要将UNIX运行器上ls命令的输出转换为GitHub Actions策略矩阵的JSON输入,现有工作流包含convert-to-matrix和build两个任务:
convert-to-matrix任务已成功生成矩阵值:[ "/etc/adduser.conf", "/etc/apt-fast.conf", "/etc/ca-certificates.conf", "/etc/cgconfig.conf", "/etc/cgrules.conf", "/etc/debconf.conf", "/etc/sudo_logsrvd.conf", "/etc/sysctl.conf", "/etc/ucf.conf", "/etc/usb_modeswitch.conf", "/etc/waagent.conf", "/etc/xattr.conf" ]build任务在评估strategy时报错:Convert LS Output to Strategy Matrix: .github#L1 Error when evaluating 'strategy' for job 'build'. .github/workflows/generateinput.yml (Line:27, Col:19): Unexpected value ''
错误原因
- 任务引用错误:
build任务错误引用了不存在的setup-matrix任务输出,实际生成矩阵的任务是convert-to-matrix;同时使用环境变量传递矩阵数据,而策略矩阵在工作流初始化阶段解析,无法读取运行时的环境变量。 - JSON生成不可靠:原脚本用
sed处理换行转义,容易出现格式错误,且转义字符"处理不当。 - 未正确使用Job输出:跨Job传递矩阵数据必须通过Job的
outputs字段,而非环境变量。
解决方案
- 用
jq生成标准JSON:替代sed处理ls输出,确保生成合法的JSON数组。 - 通过步骤输出传递数据:在
convert-to-matrix任务中,将矩阵数据作为步骤输出,再通过Job的outputs对外暴露。 - 正确引用Job输出:在
build任务的strategy中,使用needs.convert-to-matrix.outputs.matrix_values引用生成的矩阵。
修正后的完整工作流
name: Convert LS Output to Strategy Matrix on: push: branches: - main jobs: convert-to-matrix: runs-on: ubuntu-latest outputs: matrix_values: ${{ steps.matrix_step.outputs.matrix_values }} steps: - name: Get LS Output and Generate Matrix id: matrix_step run: | # 用ls获取文件列表,通过jq转为标准JSON数组 matrix_values=$(ls -1 /etc/*.conf | jq -R . | jq -s .) echo "matrix_values=$matrix_values" >> "$GITHUB_OUTPUT" build: runs-on: ubuntu-latest needs: convert-to-matrix strategy: matrix: filename: ${{ fromJSON(needs.convert-to-matrix.outputs.matrix_values) }} steps: - name: Build the file run: | echo "Building ${{ matrix.filename }}" # 这里添加针对文件的构建步骤
关键说明
jq -R .:将每行输入转为带引号的JSON字符串jq -s .:将所有字符串合并为一个JSON数组$GITHUB_OUTPUT:GitHub Actions标准的步骤输出写入路径,替代旧的set-output命令fromJSON():将字符串形式的JSON转换为GitHub Actions可解析的对象,用于策略矩阵
内容的提问来源于stack exchange,提问作者Ashar
相关产品推荐
相关产品推荐

