【问题标题】:How to save groovy output to pipeline variable如何将常规输出保存到管道变量
【发布时间】:2020-03-13 16:18:42
【问题描述】:

我在 jenkisn 管道中有以下代码:

   stage ("amd_distribution_input_transformation"){
        steps{
            script{
                    amd_distribution_input_transformation url: params.DOMAIN_DESCRIPTOR_URL, secret: params.CERDENITAL_ID
                }
            }
        }

amd_distribution_input_transformation.groovy 内容:

def call(Map parameters)
{
    def CREDENITAL_ID = parameters.secret
    def DOMAIN_DESCRIPTOR_URL = parameters.url
    sh '''
        python amd_distribution_input_transformation.py
      '''
    }             
}

在 amd_distribution_input_transformation.py 中运行了一些代码,最后它返回名为“artifacts_list”的对象

我的问题是,如何将 groovy 文件的返回对象分配给管道变量。 顺便说一句,如果它有帮助,我可以将输出从 python 代码写入 json 文件(在这里我被困在最终如何将该文件分配给管道变量)

【问题讨论】:

  • 您的 sh 方法需要一个 returnStdout 参数才能接收 Python 脚本的 JSON 输出。此外,您的 call 方法应该返回 JSON 字符串还是 Groovy 映射?

标签: python object groovy jenkins-pipeline


【解决方案1】:

sh 命令只能捕获脚本的标准输出。

所以,你不能return value from shell script。你应该打印出来。

并使用returnStdout:true 参数为sh 管道命令获取打印值。

例如你有my.py python 脚本

import json

# a Python object (dict):
x = {
  "name": "John",
  "age": 30,
  "city": "New York"
}

# convert into JSON:
y = json.dumps(x)

# print the result to transfer to caller:
print(y)

然后在管道中你可以得到python打印的json:

def jsonText = sh returnStdout:true, script: "python my.py"
def json=readJSON text: jsonText

//print some values from json:
println json.city
println "name: ${json.name}"

使用的管道步骤:

https://jenkins.io/doc/pipeline/steps/workflow-durable-task-step/#-sh-shell-script

https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readjson-read-json-from-files-in-the-workspace

【讨论】:

  • 根据您的脚本添加示例。
  • 所以这意味着最后 shOut 将包含 python 响应(artifacts_list)?然后,如何在我的管道中调用/使用它?
  • 在 python 中,您必须执行类似print artifacts_list 的操作,然后您将在 groovy 中获得此值。在 groovy 中,您至少可以做到 echo shOut。我不知道你想用它做什么......
  • 但是如何从管道使用/访问 shOut?
  • 看起来您正在扩展您的问题。请编辑问题并提供 json 的外观以及您希望如何使用它的所有详细信息...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-30
  • 2021-11-12
  • 2011-11-10
  • 1970-01-01
  • 2014-01-09
  • 2011-12-31
  • 1970-01-01
相关资源
最近更新 更多