Reputation: 12054
Jenkins scripted pipeline. Two issues:
What am i missing? (See script below)
node {
var=10
stage('HelloWorld') {
sh '''
echo "Hello World. Var=$var" ===> Prints nothing for var
var=20'''
}
stage('git clone') {
echo "Cloning git. Var = $var" ==> Prints 20, and not 10
sh '''
echo "Var in second stage is = $var" ===> Doesnt print anything here. I need 20.
'''
}
}
Upvotes: 3
Views: 10442
Reputation: 27756
Your sample doesn't work because you are using a string literal with single quotation marks. From Groovy manual (emphasis mine):
Any Groovy expression can be interpolated in all string literals, apart from single and triple-single-quoted strings.
Try this:
sh "echo 'Hello World. Var=$var'"
Or this:
sh """
echo 'Hello World. Var=$var'
echo 'More stuff'
"""
You can't directly set a Groovy variable from a shell step. This only works in one direction from Groovy to shell. Instead you can set an exit code or write data to stdout which Groovy can read.
Pass true
for parameter returnStatus
and set an exit code from the shell script which will be the return value of the sh
step.
var = sh script: 'exit 42', returnStatus: true
echo "$var" // prints 42
Pass true
for parameter returnStdout
and use echo
from shell script to output string data.
var = sh script: "echo 'the answer is 42'", returnStdout: true
echo "$var" // prints "the answer is 42"
Pass true
for parameter returnStdout
and use echo
from shell script to output string data in JSON format.
Parse JSON data in Groovy code using JsonSlurper
. Now you have a regular Groovy object that you can query.
def jsonStr = sh returnStdout: true, script: """
echo '{
"answer": 42,
"question": "what is 6 times 7"
}'
"""
def jsonData = new groovy.json.JsonSlurper().parseText( jsonStr )
echo "answer: $jsonData.answer"
echo "question: $jsonData.question"
Upvotes: 4
Reputation: 603
With withEnv
we can define & then access global var.s and at stage level if you are using declarative pipeline. For scripted one we can use temp file to access between stages as per below yielding desired output.
node {
withEnv(['var=10']){
stage('HelloWorld') {
sh '''
echo "Hello World. Var=$var" # This will print 10 from Global scope declared & defined with withEnv
var=20
# Hold that value in a file
echo 20 > ${WORKSPACE}/some.file
'''
}
stage('git clone') {
echo "Cloning git. Var = $var" // This will print 10 as well!
sh '''
v=$(<${WORKSPACE}/some.file)
echo "Var in second stage is = $v" # Get variable value from prior stage
rm -f ${WORKSPACE}/some.file
'''
}
}
}
Upvotes: 2