Issue
Right now I am a newbie for Shell, Jenkins, Groovy pipeline. My requirement is I am reading file text into a variable under shell script and I need to pass this variable value out of shell script and to use in Groovy script.
Here is my code:
stages
{
stage('example')
{
steps
{
script
{
sh'''
#!/bin/bash
set +x
readVal=$(<$WORKSPACE/test.json)
echo "$readVal" //this is priting my entire json successfully
echo 'closing shell script'
'''
println WORKSPACE /// this is printing my workspace value successfully
println readVal // not working
println env.readVal // not working
println $readVal // not working
}
}
}
}
How to get readVal
's value out of shell to access?
Solution
See Jenkins, Pipeline Best Practices:
a. Solution: Instead of using [a complex function], use a shell step and return the standard out. This shell would look something like this:
def JsonReturn = sh label: '', returnStdout: true, script: 'echo "$LOCAL_FILE"| jq "$PARSING_QUERY"'
Example
pipeline {
agent any
stages {
stage('example') {
steps {
script {
def readVal = sh script: 'echo "READ_VAL_VALUE"', returnStdout: true
echo readVal
println readVal
}
}
}
}
}
Console Output
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in C:\Users\jenkins\AppData\Local\Jenkins\.jenkins\workspace\Pipeline project
[Pipeline] {
[Pipeline] stage
[Pipeline] { (example)
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ echo READ_VAL_VALUE
[Pipeline] echo
READ_VAL_VALUE
[Pipeline] echo
READ_VAL_VALUE
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Answered By - Gerold Broser