如何将Groovy变量传递给Shell Block Jenkins

时间:2019-01-14 00:28:25

标签: jenkins groovy

我有一个groovy变量,我想将其传递给shell块以进行进一步处理,但是在下面,我一直得到错误粘贴:

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

我的错误:

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

1 个答案:

答案 0 :(得分:2)

我尝试使用您的管道(仅关闭'''范围),并且一切正常:

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

此管道的输出:

[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

因此,可能问题出在脚本的其他位置,或者您需要更新管道插件(我使用2.6版本)/ Jenkins(我使用2.150.1版本)。