output of list.py is ['test1','test2','test3']
when I use list.py in jenkins declarative pipeline to create dynamic stages,
output = sh(script: "python3 list.py", returnStdout: true )
for(int i=0; i < output.size(); i )
{
stage(output[i])
{
echo output[i]
}
}
I get the output as stage 1: [
stage 2 : t
stage 3 : e
stage 4: s ....... and so on it splits element by element
But the actual output should be, stage 1: test1
stage 2 : test2
stage 3 : test3
How to get this output ,how to split to get only the values of the list in jenkins declarative pipeline????
CodePudding user response:
output
is a string variable and not a list. (output = "['test1','test2','test3']"
)
Solution: convert output
to a list
output = sh(script: "python3 list.py", returnStdout: true ).replace('[','').replace("'",'').replace(']','').split(',')
for(int i=0; i < output.size(); i ) {
stage(output[i]) {
echo output[i]
}
}
CodePudding user response:
The returned output from a sh
(or bat
) step will always be a string, which you can then convert as needed to any other groovy object.
Because you output is actually in groovy format you can just use the evaluate
function to run the output and get it as a groovy list.
Something like:
def output = sh script: "python3 list.py", returnStdout: true
def values = evaluate "return ${output}"
values.each {
stage(it) {
echo it
}
}
You can also use def values = Eval.me("['test1','test2','test3']")
but it will require an admin approval to use the Eval
method.
An alternative will be to parse the string by yourself by removing all [
]
and '
characters from the output string and then splitting it by comma (,
).
Something like:
def output = sh script: "python3 list.py", returnStdout: true
def values = output.replaceAll(/[\[\]']/,'').tokenize(',')
values.each {
stage(it) {
echo it
}
}