Parametrized Jenkins Pipelines

Jenkins pipelines can be parametrized in the same way as traditional feestyle jobs. This post describes how.

During and after the presentation about Jenkins pipelines that I gave yesterday at the DevOps Meetup Stuttgart, we had a couple of very interesting discussions. One of them was a way to make a Jenkins pipeline job parametrized. Use cases for this that were discussed included different target environments, into which the pipeline should deploy to.

While it is not very obvious, there is one particular step that allows to configure a pipeline job’s properties, including triggers, how to rotate logs, and said input parameters: The properties step contained in the multibranch plugin. Please don’t expect too much from the referenced documentation, as it is pretty useless.

Of a lot greater help is the Snippet Editor, which is available in every Jenkins instance.

Snippet Editor

Selecting the properties step from the dropdown menu offers a whole lot of options to select, including This project is parameterized. After checking this option, parameters of different kinds can be added, i.e., boolean, string, select parameters etc.

Adding a string parameter

Hitting the Generate Pipeline Script button emits the following code snippet (manually formatted by myself):

properties([
  parameters([
    string(name: 'DEPLOY_ENV', defaultValue: 'TESTING', description: 'The target environment', )
   ])
])

Once this code is included at the top level of the pipeline script, any pipeline execution resets the job’s parameters to the specified values. From that point on, the Build Now button has changed to a Build with Parameter and every time the pipeline is launched, the user is asked to specify defined values.

Build with parameters

P.S: The first run will most likely fail (EDIT: see last paragraph), as chances are good that you try to access the just added parameters (JENKINS-40235). Subsequent runs will work, if your pipeline script is correct.

Bonus: Selection from Dropdown

Using the Choice Parameter, the possible inputs can be restricted to a pre-defined list of choices.

Adding a choice parameter

Be warned that the emitted code including choices: ['TESTING', 'STAGING', 'PRODUCTION'] fails with an exception

java.lang.ClassCastException: hudson.model.ChoiceParameterDefinition.choices expects class java.lang.String but received class java.util.ArrayList

Instead, the list of choices has to be supplied as String containing new line characters (\n): choices: ['TESTING\nSTAGING\nPRODUCTION'] (JENKINS-40358).

EDIT January, 12th: Previously, it was common to access these parameters using Groovy or environment variables:

echo "Will deploy to ${DEPLOY_ENV}"

As of workflow-cps version 2.18, a new params global variable provides sane access also on the first run (by returning specified default values).

echo "Will deploy to ${params.DEPLOY_ENV}"