Jenkins Pass Variables between Stages

今天遇到一个问题,如何将在一个stage中产生的变量,传递到另一个stage中。一种解决办法是使用global variable, for example, in declarative pipeline:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// variable to be used
def jobBaseName

stage ('Construct Img name') {
// this is from scripted pipeline syntax
jobBaseName = sh(
script: "echo ${BUILD_TAG} | awk '{print tolower($0)}' | sed 's/jenkins-//'",
returnStdout: true
)
}

stage ('Build Target Container') {
sh "ssh -i ~/ssh_keys/key.key user@somehost 'cd /dockerdata/build/${BUILD_TAG} && docker build -t localrepo/${jobBaseName}:${BUILD_NUMBER} .'"
}

还有人通过将变量写入文件中,再从另一个stage读取加载的方式,但这需要保证Stages are running on the same node agent.

此外,关于Jenkins中的environment variablebuild parameters,有如下需要注意的地方: https://stackoverflow.com/questions/50398334/what-is-the-relationship-between-environment-and-parameters-in-jenkinsfile-param

Basically it works as follow

  • env contains all environment variables, for example: env.BUILD_NUMBER
  • Jenkins pipeline automatically creates a global variable for each environment variable
  • params contains all build parameters, for example: params.WKC_BUILD_NUMBER
  • Jenkins also automatically creates an environment variable for each build parameter (and as a consequence of second point a global variable).

Environment variables can be overridden or unset (via Groovy script block) but params is an immutable Map and cannot be changed. Best practice is to always use params when you need to get a build parameter.

这些信息哪里来的呢?在配置pipeline时,查看pipeline syntax -> Global Variables Reference.

0%