如何将本地JSON作为GitHub Actions workflow_dispatch的参数使用?
解决GitHub Actions传递JSON参数失败的问题
问题背景
需将本地JSON文件中的配置参数传入GitHub Actions测试脚本,通过gh workflow run命令触发工作流。当前使用setup.yml作为触发工作流,调用single-device-authentication.yml子工作流,但在子工作流中输出inputs.config_file时失败。
触发命令:
gh workflow run setup.yml -f config_file="$(cat ${PATH_TO_CONFIG_FILE})"
原setup.yml内容:
name: setup on: workflow_dispatch : inputs: config_file: description: 'json file containing the configuration for the runners' required: true type: string ... env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} jobs: setup-auth: name: setup-authentication uses: ./.github/workflows/single-device-authentication.yml with: devices: mlops config_file: ${{ inputs.config_file }} secrets: inherit
原single-device-authentication.yml失败部分:
jobs: json-parser: name: parser runs-on: ${{inputs.devices}} needs: device-authentication steps: - name: parser script run: | echo ${{ inputs.config_file }} # 此处执行失败
失败原因
JSON内容包含引号、大括号、换行等特殊字符,直接作为字符串传递时:
- 会与Shell命令的引号语法冲突,导致命令解析错误;
- GitHub Actions的表达式解析器会将JSON中的特殊字符视为语法的一部分,引发解析异常。
解决方案
1. 传递前对JSON进行Base64编码
修改触发命令,将JSON内容转为Base64编码后传递,避免特殊字符干扰:
gh workflow run setup.yml -f config_file="$(cat ${PATH_TO_CONFIG_FILE} | base64 -w 0)"
-w 0参数用于禁用Base64输出的自动换行,确保传递的是完整的单行字符串。
2. 子工作流中解码并使用JSON
在single-device-authentication.yml的解析步骤中,先对Base64内容解码,再保存为JSON文件或直接处理:
jobs: json-parser: name: parser runs-on: ${{inputs.devices}} needs: device-authentication steps: - name: parser script run: | # 解码Base64内容并保存为config.json echo "${{ inputs.config_file }}" | base64 -d > config.json # 验证文件内容 cat config.json # 可选:使用jq工具提取JSON字段(需确保 runner 已安装jq) # jq '.your_key' config.json
3. 跨平台兼容(可选)
如果在Windows环境下执行触发命令,替换base64命令为Windows自带的certutil:
# 编码 certutil -encode config.json temp.b64 && findstr /v /c:- temp.b64 > config.b64 gh workflow run setup.yml -f config_file="$(type config.b64)" # 子工作流解码 echo "${{ inputs.config_file }}" > config.b64 && certutil -decode config.b64 config.json
内容的提问来源于stack exchange,提问作者Maxime Debarbat
相关产品推荐
相关产品推荐

