【问题标题】:jq in a Jenkins pipeline not saving output to variablejq 在 Jenkins 管道中没有将输出保存到变量
【发布时间】:2021-11-10 20:53:21
【问题描述】:

所以在我的 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-pipeline jq


    【解决方案1】:

    您将true 作为returnStdout 参数的参数传递给stageTwoList 的shell step 方法,但随后忘记对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 Pipeline 步骤方法来简化此操作:

    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']
    

    【讨论】:

    • 谢谢 - 这行得通。也会在 GROOVY 中尝试原生的 JSON 解析。没想到。
    猜你喜欢
    • 2020-03-13
    • 2022-09-27
    • 2011-11-10
    • 1970-01-01
    • 2017-04-16
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    相关资源
    最近更新 更多