arielma
arielma

Reputation: 1398

How to save groovy output to pipeline variable

I have the below code in the jenkisn pipeline:

   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 content:

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

in the amd_distribution_input_transformation.py some code is running, and at the end, it returns object named 'artifacts_list'

my question is, how can I assign the return obect from groovy file to pipeline variable. BTW, if it helps, I can write the output to json file from the python code (and here I'm stuck on how eventually assign that file to the pipeline variable)

Upvotes: 1

Views: 2674

Answers (1)

daggett
daggett

Reputation: 28634

sh command could catch only standard output from script.

So, you could not return value from shell script. You should print it.

And use returnStdout:true parameter for sh pipeline command to get printed value.

For example you have my.py python script

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)

Then in pipeline you could get the json printed by python:

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}"

Used pipeline steps:

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

Upvotes: 1

Related Questions