首页 > 解决方案 > jq 在 Jenkins 管道中没有将输出保存到变量

问题描述

因此,在我的 Jenkins 管道中,我在不同阶段运行了几个 curl 命令。我将 Stage1 的输出存储到一个文件中,并且对于该列表中的每个项目,我运行另一个 curl 命令并使用该输出通过 jq 提取一些值。

但是,从第二阶段开始,我似乎无法将 jq 提取的值存储到变量中以便稍后回显它们。我究竟做错了什么?

{Stage1}
.
.
.
{Stage2}
def lines = stageOneList.readLines()
lines.each { line -> println line
                        
stageTwoList = sh (script: "curl -u $apptoken" + " -X GET --url " + '"' + "$appurl" + "components/tree?component=" + line + '"', returnStdout: true)                                
pfName = sh (script: "jq -r '.component.name' <<< '${stageTwoList}' ")
pfKey = sh (script: "jq -r '.component.key' <<< '${stageTwoList}' ")
echo "Component Names and Keys\n | $pfName | $pfKey |"
}

最终返回 Stage2

[Pipeline] sh
+ jq -r .component.name
digital-hot-wallet-gateway
[Pipeline] sh
+ jq -r .component.key
dhwg
[Pipeline] echo
Component Names and Keys
 | null | null |

对正确方向的任何帮助表示赞赏!

标签: jenkins-pipelinejq

解决方案


true将参数作为returnStdout参数传递给 shell step 方法stageTwoList,但后来忘记使用相同的参数来解析 JSON 并返回到接下来的两个变量赋值:

def lines = stageOneList.readLines()
lines.each { line -> println line
                    
  stageTwoList = sh(script: "curl -u $apptoken" + " -X GET --url " + '"' + "$appurl" + "components/tree?component=" + line + '"', returnStdout: true)                                
  pfName = sh(script: "jq -r '.component.name' <<< '${stageTwoList}' ", returnStdout: true)
  pfKey = sh(script: "jq -r '.component.key' <<< '${stageTwoList}' ", returnStdout: true)
  echo "Component Names and Keys\n | $pfName | $pfKey |"
}

请注意,您还可以通过在 Groovy 中进行原生 JSON 解析并使用 Jenkins 流水线步骤方法来简化此操作:

String stageTwoList = sh(script: "curl -u $apptoken" + " -X GET --url " + '"' + "$appurl" + "components/tree?component=" + line + '"', returnStdout: true)
Map stageTwoListData = readJSON(text: stageTwoList)
pfName = stageTwoListData['component']['name']
pfKey = stageTwoListData['component']['key']

推荐阅读