Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a groovy variable to a shell block jenkins

Tags:

jenkins

groovy

I have a groovy variable that i would like to pass to a shell block for further processing, but i keep getting the error pasted bellow:

stages {      
    stage('First Stage - echo out available variables'){
        steps{

            script {
                def string_var = "im a groovy variable"
                echo "${string_var}"   // This will print "im a groovy variable" just fine
                sh """
                    echo """ + string_var + """
                """  // This will error

                sh """
                    echo ${string_var} 
                """  // This will error

                sh ''' echo '''+ string_var +''' '''

                sh "echo ${string_var}" // This will error
            }
        }
    }
}

My error:

an exception which occurred:
    in field com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@1ecb37ba
    in field com.cloudbees.groovy.cps.impl.CallEnv.caller
    in object com.cloudbees.groovy.cps.impl.FunctionCallEnv@32070c3b
    in field com.cloudbees.groovy.cps.Continuable.e
    in object org.jenkinsci.plugins.workflow.cps.SandboxContinuable@641113f0
like image 340
BLang Avatar asked Jan 26 '23 21:01

BLang


1 Answers

I tried to use your pipeline (just closed ''' scopes) and everything works fine:

pipeline {
    agent any
    stages {      
        stage('First Stage - echo out available variables'){
            steps{
                script {
                    def string_var = "im a groovy variable"
                    echo "${string_var}"

                    sh """
                        echo """ + string_var + """
                    """

                    sh """
                        echo ${string_var} 
                    """ 

                    sh ''' echo '''+ string_var +''' ''' // added '''

                    sh "echo ${string_var}"
                }
            }
        }
    }
}

Output for this pipeline:

[Pipeline] {
[Pipeline] stage
[Pipeline] { (First Stage - echo out available variables)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
im a groovy variable
[Pipeline] sh
+ echo im a groovy variable
im a groovy variable
[Pipeline] sh
+ echo im a groovy variable
im a groovy variable
[Pipeline] sh
+ echo im a groovy variable
im a groovy variable
[Pipeline] sh
+ echo im a groovy variable
im a groovy variable
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

So, probably the problem is in some other place of script, or you need to update Pipeline Plugin (I use 2.6 version) / Jenkins (I use 2.150.1 version).

like image 180
biruk1230 Avatar answered Feb 23 '23 15:02

biruk1230