Jenkins脚本化管道:无法在Shell中打印变量并在Shell中设置变量值

时间:2020-02-28 09:52:45

标签: jenkins jenkins-groovy

Jenkins脚本化管道。两个问题:

  1. 我有一个全局变量var,我正在尝试访问其值 贝壳。但它什么也没打印
  2. 我在其中一个阶段使用一个 shell脚本,可以在下一个阶段访问,但是在shell中什么也不会打印。

我想念什么? (请参见下面的脚本)

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

2 个答案:

答案 0 :(得分:2)

1。将常规变量传递给shell

您的示例不起作用,因为您使用的是带单引号的字符串文字。来自Groovy manual(重点是我):

任何Groovy表达式都可以插入所有字符串文字中, 除了三重单引号字符串。

尝试一下:

sh "echo 'Hello World. Var=$var'"

或者这个:

sh """
    echo 'Hello World. Var=$var'
    echo 'More stuff'
"""        

2。从shell设置Groovy变量

您不能直接在Shell步骤中设置Groovy变量。从Groovy到Shell,这仅在一个方向上起作用。相反,您可以设置退出代码或将数据写入Groovy可以读取的stdout。

返回单个整数

为参数true传递returnStatus并从shell脚本中设置退出代码,该代码将是sh步骤的返回值。

var = sh script: 'exit 42', returnStatus: true
echo "$var"   // prints 42

返回单个字符串

为参数true传递returnStdout并在shell脚本中使用echo输出字符串数据。

var = sh script: "echo 'the answer is 42'", returnStdout: true
echo "$var"   // prints "the answer is 42"  

返回结构化数据

true传递给参数returnStdout,并从shell脚本中使用echo以JSON格式输出字符串数据。

使用JsonSlurper解析Groovy代码中的JSON数据。现在,您有了可以查询的常规Groovy对象。

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"

答案 1 :(得分:2)

使用withEnv,我们可以定义&然后访问全局变量,如果您使用声明性管道,则可以在阶段级别进行访问。对于脚本化脚本,我们可以使用临时文件按照以下所示在阶段之间进行访问,以产生所需的输出。

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

    }
}