首页 > 解决方案 > 如何将常规输出保存到管道变量

问题描述

我在 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 文件(在这里我坚持如何最终将该文件分配给管道变量)

标签: pythonobjectgroovyjenkins-pipeline

解决方案


shcommand 只能捕获脚本的标准输出。

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

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

例如你有my.pypython 脚本

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


推荐阅读