Jenkins脚本化管道。两个问题:
我想念什么? (请参见下面的脚本)
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.
'''
}
}
答案 0 :(得分:2)
您的示例不起作用,因为您使用的是带单引号的字符串文字。来自Groovy manual(重点是我):
任何Groovy表达式都可以插入所有字符串文字中, 除了单和三重单引号字符串。
尝试一下:
sh "echo 'Hello World. Var=$var'"
或者这个:
sh """
echo 'Hello World. Var=$var'
echo 'More stuff'
"""
您不能直接在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
'''
}
}
}