如何在GitHub Actions工作流中访问动态命名的变量值
问题原因解析
你的写法错误有两个核心原因:
- 你
buildjob的逻辑存在判断错误:if [ ${{ matrix.index }} = "dev" ]中的matrix.index的值是1/2,dev是matrix.deploy的取值,这个判断永远为假,会导致c_ip1输出永远为空。 - Bash的间接变量展开
${!val}只能读取当前shell环境内的变量,而needs.build.outputs.*是GitHub Actions的内置上下文变量,会在shell脚本运行前完成预解析替换,脚本运行时shell根本不存在needs.build.outputs.c_ip1这类变量,自然无法读取。
正确实现方案
使用GitHub Actions内置的fromJSON+format函数组合,直接在Actions表达式层面完成动态变量名拼接和取值,不需要依赖shell的变量展开能力。
修正后的完整工作流配置
on: [push] jobs: build: runs-on: ubuntu-latest outputs: c_ip1: ${{ steps.set_c.outputs.c_ip1 }} c_ip2: ${{ steps.set_c.outputs.c_ip2 }} strategy: matrix: include: - index: 1 deploy: "dev" - index: 2 deploy: "prod" steps: - id: set_c run: | # 修正判断条件,改为判断matrix.deploy if [ ${{ matrix.deploy }} = "dev" ]; then res=10 echo "::set-output name=c_ip1::$res" else res=5 echo "::set-output name=c_ip2::$res" fi continue-on-error: true upgrade-c2: name: another job needs: build runs-on: ubuntu-latest strategy: matrix: include: - index: 1 deploy: "dev" - index: 2 deploy: "prod" steps: - run: | if [ ${{ matrix.deploy }} = "dev" ]; then # 动态取值核心写法 echo ${{ fromJSON(format('{0}', needs.build.outputs))[format('c_ip{0}', matrix.index)] }} else echo ${{ fromJSON(format('{0}', needs.build.outputs))[format('c_ip{0}', matrix.index)] }} fi continue-on-error: true
写法说明
format('c_ip{0}', matrix.index):根据matrix的index值动态拼接出c_ip1/c_ip2的变量名fromJSON(format('{0}', needs.build.outputs)):将needs.build.outputs对象转为可通过字符串索引访问的结构,搭配上面拼接的变量名就能动态取到对应的值
如果偏好shell层面处理,也可以先把所有output导出为JSON再用jq取值:
- run: | # 先把所有outputs导出为json存入shell变量 outputs='${{ toJSON(needs.build.outputs) }}' ip=${{ matrix.index }} # 用jq动态取值 echo $(echo $outputs | jq -r ".c_ip$ip")
这样也能得到正确结果。
内容的提问来源于stack exchange,提问作者stack007 stack007
相关产品推荐
相关产品推荐

