Jenkins - Using Different Parameters For Different Environment Branches
The Problem
I want to create a Jenkinsfile that will be responsible for building and deploying an open source project. The Jenkinsfile will be committed to the public git repository so anybody can use it. Thus the settings can't be in the actual Jenkinsfile itself. Instead, the settings need to be injected by the Jenkins server at the point of running.
Also, I have "environment branches" (GitLab flow), so I would like Jenkins to automatically use different sets of settings based on which environment branch is being run. E.g. when I push to the "staging" branch, I would like the "host" parameter to be set to whatever the staging server is.
The Solution
Install the "Config File Provider" plugin.
Then click on Config Files.
Click Add a New Config.
Select JSON for the file type.
Give the config file a name, and then fill in the body of the config file with your relevant settings.
Notice that the keys master
, staging
, and production
, for the master
, staging
, and production
branches.
Within each of those set any number of parameter names, with the appropriate values.
Once you submit, you should see your config file there, with its ID.
You can now use it for fetching parameters based on the branch, as shown below:
stage("build") {
steps {
configFileProvider([configFile(fileId: 'myConfigFileId', variable: 'settingsFile')]) {
script {
def config = readJSON file:"$settingsFile"
def branchConfig = config."${env.BRANCH_NAME}"
if (branchConfig) {
def host = branchConfig.host
echo "The host for the ${env.BRANCH_NAME} branch is: ${host}"
}
else {
error("Build failed because failed to fetch settings for branch")
}
}
}
}
}
References
First published: 5th May 2021