My project has many common variables for many other projects, so I use Jenkins Shared Library and created a vars/buildMeta.groovy
file where I defined my variables (some sh
parse functions), and use them at the environment stage (var1, var2):
pipeline {
environment {
// initialize common vars
var1 = buildMeta.getVar1()
var2 = buildMeta.getVar2()
varA = var1 + "some_string"
varB = var2 + "some_other_string"
} // environment
stages {
stage('Some Stage') {
// ...
}
}
post {
always {
script {
// Print environment variables
sh "env"
} // script
} // always
} // post
} // pipeline
I decided to export the varA
, varB
to a shared vars/my_vars.groovy
and use them from there (when I must to transfer the config Map with the var1
, var2
vars).
class my_vars {
static Map varMap = [:]
static def loadVars (Map config) {
varMap.varA = config.var1 + "some_string"
varMap.varB = config.var2 + "some_other_string"
// Many more variables ...
return varMap
}
}
The thing is, for declaring those vars as environment vars I used that way:
pipeline {
my_vars.loadVars().each { key, value ->
env[key] = value
}
environment {
// initialize common vars
var1 = buildMeta.getVar1()
var2 = buildMeta.getVar2()
} // environment
stages {
stage('Some Stage') {
// ...
}
}
// ...
} // pipeline
but that way the buildMeta vars (var1, var2) are nor defined yet, so I can not initialized properly the my_vars.loadVars()
call.
On the other hand I can't duplicate the buildMeta.groovy
functions to my_vars.loadVars()
since there are an sh
usage at the former, and the call for the latter is not defined under a stage (script).
I've could to solve all this by putting all those functions calls at a seperate stage (lets say 'Load Variables' stage) but I really want to avoid that dummy stage. What is the best practice for that?
Thanks!