如何将 groovy 变量传递给 shell 块 jenkins

BLa*_*ang 3 groovy jenkins

我有一个 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
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的错误:

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
Run Code Online (Sandbox Code Playgroud)

bir*_*230 8

我尝试使用您的管道(只是封闭的'''范围)并且一切正常:

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}"
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此管道的输出:

[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
Run Code Online (Sandbox Code Playgroud)

所以,问题可能出在脚本的其他地方,或者您需要更新 Pipeline Plugin(我使用 2.6 版本)/ Jenkins(我使用 2.150.1 版本)。