【问题标题】:Not getting variable value in jenkinsfile没有在 jenkinsfile 中获取变量值
【发布时间】:2020-03-16 13:21:10
【问题描述】:

我正在使用下面的Jenkinsfile。它在使用jq 命令执行时正在打印upload_id 的值,但是在打印该值时它显示null

请帮我解决这个变量问题。

sh label: '', script: 'upload_id=$(cat output_file.json | jq -r \'.upload_id\')'
sh "echo \"$upload_id\""**

输出:

[管道] sh 猫输出文件.json jq -r .upload_id upload_id=8f304c6d-804b-440a-xxxx** [管道] sh 回声上传ID:空 upload_id:空
[管道]}

【问题讨论】:

  • 它显示带有 jq 参数的上传 ID,但在打印值时显示 null 输出:[管道] sh + cat output_file.json + jq -r .upload_id + upload_id=8f304c6d-804b-440a -8db3-xxxx [管道] sh + echo upload_id : null upload_id : null [管道] }
  • 您能否根据您的建议建议我如何使用上述两个命令。 1. sh 标签:'',脚本:'upload_id=$(cat output_file.json | jq -r \'.upload_id\')' 2. sh "echo \"$upload_id\""**
  • 在您的情况下,my answer 的“返回单个字符串”部分将适用。
  • 这里,我使用的是流水线脚本。像 pipeline{ stage { stage() { steps{ sh label: '', script: 'upload_id=$(cat output_file.json | jq -r \'.upload_id\')' sh "echo \"$upload_id 一样编写此代码\"}}}。你能建议我如何在这里使用来获取 user_id 的值。输出:[Pipeline] sh cat output_file.json jq -r .upload_id upload_id=8f304c6d-804b-440a-xxxx** [Pipeline ] sh echo upload_id : null upload_id : null [管道] }

标签: shell variables jenkins-pipeline jq


【解决方案1】:

我强烈推荐使用Matt's answer,因为这是最干净的方式。

反正有些情况,除了使用shell别无选择,所以这里是shell方式:

script {
    def upload_id = sh label: '', 
                       script: 'echo $(cat output_file.json | jq -r \'.upload_id\')', 
                       returnStdout: true
    upload_id = upload_id.trim()  // remove extraneous whitespace
    sh "echo \"$upload_id\""
}

我已经链接到更多detailed answer of mine,但您可能没有让它工作,因为您使用的是声明性管道。在声明式管道中,您必须使用 script 块才能存储步骤的返回值。

【讨论】:

  • 非常感谢您帮助我。现在它工作正常。但是有一个问题。它在值中增加了一行。请帮助解决问题。 + echo 上传 id:6b84fd50-8036-447c-84fa-xxxxxxxx 上传 id:6b84fd50-8036-447c-xxxxxxxxxxxx [管道] sh
  • @Raghunath 我添加了一个 trim() 来删除多余的行。
【解决方案2】:

您可以在 Jenkins Pipeline 中轻松地做到这一点,以避免子流程执行的所有问题。首先,读入并解析 JSON 文件:

upload_info = readJSON(file: 'output_file.json')

然后,您就可以正常访问分配的upload_info Map 中的返回值了:

upload_id = upload_info['upload_id']

【讨论】:

  • 出现此错误 - sh:“语法错误:”(“意外”。我在步骤下使用以下命令{ sh "upload_info = readJSON(file: 'output_file.json')" sh "upload_id = upload_info['upload_id']" echo "$upload_id" }
  • @RaghunathDhara 我不确定你在那里写了什么,但这不是我的回答。请使用我的答案。
  • 这里,我使用的是流水线脚本。像 pipeline{ stage { stage() { steps{ sh label: '', script: 'upload_id=$(cat output_file.json | jq -r \'.upload_id\')' sh "echo \"$upload_id 一样编写此代码\"}}}。你能建议我如何在这里使用来获取 user_id 的值。输出:[Pipeline] sh cat output_file.json jq -r .upload_id upload_id=8f304c6d-804b-440a-xxxx** [Pipeline ] sh echo upload_id : null upload_id : null [管道] }
猜你喜欢
  • 1970-01-01
  • 2018-10-13
  • 2019-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
相关资源
最近更新 更多