Looking for a Jenkins plugin to allow per-branch default parameter values

Viewed 1253

I have a multi-branch pipeline job set to build by Jenkinsfile every minute if new changes are available from the git repo. I have a step that deploys the artifact to an environment if the branch name is of a certain format. I would like to be able to configure the environment on a per-branch basis without having to edit Jenkinsfile every time I create a new such branch. Here is a rough sketch of my Jenkinsfile:

pipeline {
  agent any

  parameters {
    string(description: "DB name", name: "dbName")
  }

  stages {
    stage("Deploy") {
      steps {
        deployTo "${params.dbName}"
      }
    }
  }
}

Is there a Jenkins plugin that will let me define a default value for the dbName parameter per branch in the job configuration page? Ideally something like the mock-up below:

plugin UI mock-up

The values should be able to be reordered to set priority. The plugin stops checking for matches after the first one. Matching can be exact or regex.

If there isn't such a plugin currently, please point me to the closest open-source one you can think of. I can use it as a basis for coding a custom plugin.

3 Answers

Here is a workaround :

Using the Jenkins Config File Provider plugin create a config json with parameters defined in it per branch. Example:

 {
  "develop": {
    "dbName": "test_db",
    "param2": "value"
  },
  "master": {
    "dbName": "prod_db",
    "param2": "value1"
  },
  "test_branch_1": {
    "dbName": "zss_db",
    "param2": "value2"
  },
  "default": {
    "dbName": "prod_db",
    "param2": "value3"
  }
}

In your Jenkinsfile:

final commit_data = checkout(scm)
BRANCH = commit_data['GIT_BRANCH']
configFileProvider([configFile(fileId: '{Your config file id}', variable: 'BRANCH_SETTINGS')]) {
                def config = readJSON file:"$BRANCH_SETTINGS"
                def branch_config = config."${BRANCH}"

                if(branch_config){
                    echo "using config for branch ${BRANCH}"
                }
                else{
                    branch_config = config.default                      
                }
                echo branch_config.'dbName'
}

You can then use branch_config.'dbName', branch_config.'param2' etc. You can even set it to a global variable and then use throughout your pipeline.

The config file can easily be edited via the Jenkins UI(Provided by the plugin) to provision for new branches/params in the future. This doesn't need access to any non sandbox methods.

Not really an answer to your question, but possibly a workaround...

I don't know that the rest of your parameter list looks like, but if it is a static list, you could potentially have your static list with a "use Default" option as the first one.

When the job is run, if the value is "use Default", then gather the default from a file stored in the SCM branch and use that.

Related