如何在GitHub Action中批量传递参数至其他步骤?
批量传递GitHub Action步骤输出的解决方案
你遇到的问题核心在于GitHub Actions的with参数仅支持字符串类型——直接传递steps.hello-action.outputs这个对象时,会被强制转换成字符串[object Object],自然无法访问内部属性。下面给你两种实用的批量传递方法:
方法一:用toJSON函数序列化输出对象
GitHub Actions内置了toJSON函数,可以把对象序列化为合法的JSON字符串,接收端再解析成对象即可。
修改Workflow配置
把传递参数的部分改成:
- name: run hello2 action id: hello2-action run: node index2.js with: outputs: ${{ toJSON(steps.hello-action.outputs) }}
修改接收端代码(index2.js)
拿到JSON字符串后解析成对象:
const core = require("@actions/core"); const outputsStr = core.getInput("outputs"); // 解析为对象 const outputs = JSON.parse(outputsStr); console.log("hello2 outputs:", outputs); // 输出完整对象 console.log("hello2 outputs.res1:", outputs.res1); // 可以正常访问res1的值
方法二:在源步骤输出合并的JSON字符串
如果需要更灵活地控制传递的内容,可以在第一个步骤里直接把所有输出整合成一个JSON字符串输出:
修改源步骤代码(index.js)
const core = require("@actions/core"); // 先定义所有输出内容 const outputData = { res1: "res1", res2: "res2", res3: "res3" }; // 输出单个JSON格式的output core.setOutput("combined", JSON.stringify(outputData)); // 保留原有单个输出(如果需要的话) core.setOutput("res1", "res1"); core.setOutput("res2", "res2"); core.setOutput("res3", "res3");
修改Workflow配置
传递这个合并后的JSON输出:
- name: run hello2 action id: hello2-action run: node index2.js with: outputs: ${{ steps.hello-action.outputs.combined }}
接收端代码(index2.js)
和方法一一样,解析JSON字符串即可:
const core = require("@actions/core"); const outputsStr = core.getInput("outputs"); const outputs = JSON.parse(outputsStr); console.log("hello2 outputs.res2:", outputs.res2); // 正常访问属性
为什么原来的方法不行?
GitHub Actions的with输入参数只接受字符串类型,当你直接传递对象类型的steps.hello-action.outputs时,GitHub会自动调用对象的toString()方法,结果就是[object Object]——这只是一个普通字符串,不是可解析的对象,所以访问outputs.res1会得到undefined。
内容的提问来源于stack exchange,提问作者negabaro
相关产品推荐
相关产品推荐

