Filed under: Automation, Continuous integration, DevOps, — Tags: Jenkins, Jenkinsfile, pipeline — Thomas Sundberg — 2019-11-26
I have a situation where I want two jobs in Jenkins to have the same definition. They will run a set of tests against two different environments.
I want to name the jobs so it is obvious which environment they target. My naming schema looks like this:
*-dev
The jobs will therefore be named as:
integration-tests-dev
integration-tests-sys
How can I use the same job definition using a Declarative Pipeline and change the target environment easily?
I can define a build Pipeline in Jenkins, but I can't send arguments to it from the job definition.
In my world as a developer, a good solution would have been something like this in the field Script Path:
Jenkinsfile dev
using a positional parameter dev
. This, however, it is not supported.
The job names are different and I can use that.
It turns out that the Jenkinsfile
, where the pipleline is defined, is a Groovy script.
I can do stuff above the line pipeline {
in this script.
This is great because it alows me to do stuff like this:
def MAVEN_PROFILE = 'default'
if (env.JOB_NAME.endsWith('-sys')) {
MAVEN_PROFILE = 'systest'
}
pipeline {
.
.
.
This piece of code defines a variable. It defaults to default
but if the job name ends with -sys
it is
set to another value. In this case systest
.
The result is that I can see which environment I should target for each job based on its name. This is perhaps even better than using a positional parameter in the job definition. It simplifies the maintenance of the jobs.
How do I use the variable?
I my case, I use it for invoking Maven with the proper profile. I'm not happy with that solution, but it is a solution I inherited and I don't want to change more than one thing at a time. My current focus is the execution of the job and reduce the duplication I inherited.
Using the variable MAVEN_PROFILE
is done like this:
stage('Run integration tests') {
steps {
sh "mvn clean test -P${MAVEN_PROFILE}"
}
}
The magic is ${MAVEN_PROFILE}
where the value in the variable is expanded.
Using Groovy to evaluate the name of the current job allows me to use the same definition for two Jenkins jobs with different names and target environments.
I would like to thank Malin Ekholm and Mika Kytöläinen for feedback.