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.
'''
}
}
使用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
'''
}
}
}
这不起作用,因为您正在使用带单引号的字符串文字。从Groovy manual(强调我的):
任何Groovy表达式都可以插入所有字符串文字中,除了single和triple-single-quoted字符串。
您不能直接在Shell步骤中设置Groovy变量。从Groovy到Shell,这仅在一个方向上起作用。但是,您可以设置退出代码,并通过为参数sh
传递true
从returnStatus
步骤返回该代码:
stage('HelloWorld') {
var = sh script: 'exit 42', returnStatus: true
echo "$var" // prints 42
}
如果数据更复杂,则可以将true
传递给参数returnStdout
,使用Shell脚本中的echo
输出数据并解析从sh
步骤返回的字符串:
stage('HelloWorld') {
var = sh script: "echo 'the answer is 42'", returnStdout: true
echo "$var" // prints "the answer is 42"
}