Jenkins Pipeline Parameters: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 68: Line 68:
==File Parameter==
==File Parameter==
[[Jenkins_Pipeline_Syntax#Scripted_Pipeline|Scripted pipeline]] syntax:
[[Jenkins_Pipeline_Syntax#Scripted_Pipeline|Scripted pipeline]] syntax:
<font color=darkgray>TODO</font>


==Choice Parameter==
==Choice Parameter==

Revision as of 23:06, 23 March 2021

External

Internal

Overview

A parameter is a way to configure a pipeline. If you think of a pipeline as a function, then a parameter is the function's argument. When a parameterized build is in the queue, an attempt to start another build of the same project will only succeed if the parameter values are different, or if the "Execute concurrent builds if necessary" option is enabled.

A pipeline that exposes parameters enables parameterized builds and its UI will offer the choice to "Build with Parameters":

Build with Parameters.png


Parameters can be declared in the pipeline's Jenkinsfile, in the UI when the pipeline is created, or in both. For a discussion on parameter declaration, see Parameter Declaration below.

The parameters of a certain pipeline instance can be accessed at runtime from Jenkinsfile via this.params, which is a Map that maintains parameter name - parameter value association. For more details on accessing parameters see Accessing Parameters below. For more details about the data structures associated with a pipeline at runtime see:

Scripted Pipeline at Runtime

Parameter Declaration

The preferred way to define pipeline parameters is to declare them in Jenkinsfile. It is also possible to declare them in the pipeline UI, when the pipeline is defined.

If different parameters are declared in UI and Jenkinsfile, the build will be unstable for the first run, when a union of the parameters declared in the UI and Jenkinsfile will be available to the pipeline. After the build finishes successfully, the Jenkinsfile parameter declaration is used as authoritative source of parameters, and their definitions will overwrite the parameters originally defined in the UI, so if "Build with Parameters" is used after the first run, only the Jenkinsfile-declared parameters show up in the UI.


If your build uses a Jenkinsfile that declares parameters, it is NOT a good idea to declare parameters in the UI. Always use the Jenkinsfile as the authoritative source of parameter definitions. When creating the pipeline, do not specify any parameters in the UI, just use "Build Now" to run it once giving Jenkinsfile a chance to be parsed and loaded, and the Jenkinsfile parameters will be available in the UI during the next run.

Jenkinsfile Parameters

A parameter is declared in the pipeline's Jenkinsfile using a different syntax depending on whether the pipeline is declarative or scripted.

Scripted Pipeline Parameter Declaration

Parameters can be declared a scripted pipeline Jenkinsfile using the syntax shown below:

properties([
  parameters([
    string(name: 'color', defaultValue: 'blue', description: 'The build color'),
    ...
  ])
])

For a full list of parameter types that can be added see Parameter Types below.

Parameter Definition Update Cycle


If a parameter is added, removed or modified in Jenkinsfile, which is then checked into repository, the change will not immediately reflect in the "Build with Parameters" UI. Initiate a build with the old parameters, and stop it as soon as the Jenkinsfile is loaded and parsed from the repository. Only the, the change will reflect in "Build with Parameters" UI.

UI Parameters

The parameters can be declared in the UI when the pipeline is defined by checking the "This project is parameterized" box in the General settings tab. This will give access to an interface that allows adding individual parameters, turning the build into a parameterized build. For a full list of parameter types that can be added see Parameter Types below.

⚠️ As mentioned in the Parameter Declaration section above, if your build uses a Jenkinsfile that declares parameters, do not use UI-declared parameters, always rely on the parameters declared in Jenkinsfile.

Parameter Types

String Parameter

Scripted pipeline syntax:

properties([
   parameters([
        string(name: 'color', defaultValue: 'blue', description: 'The build color')
   ])
])

File Parameter

Scripted pipeline syntax:

TODO

Choice Parameter

Scripted pipeline syntax:

properties([
  parameters([
    choice(name: 'size', choices: ['S', 'M', 'L'],  description: 'Size choice (S/M/L)')
])

Custom Parameters

TODO: https://wiki.jenkins.io/display/jenkins/parameterized+build

Setting Parameter Values

If parameters are defined in Jenkinsfile, defaults can be set there using the defaultValue: '...' syntax. Those defaults will reflect in the UI after a build cycle, as described in the Parameter Definition Update Cycle section.

Accessing Parameters

The Map containing the build's parameters can be accessed at runtime from the Jenkinsfile with:

this.params

The existence of a parameter can be checked with:

print "exists: " + this.params.containsKey(paramName)

If the parameter exists, its value can be accessed with:

def paramName = "color"
print "parameter value: " + this.params.get(paramName)

or with:

print "parameter value: " + this.params.color

If the parameter does not exist in the map, both examples will print "parameter value: null".

Parameters as Environment Variables

The parameters are available as environment variables. So e.g. a shell ($FOO, %FOO%) or Ant ( ${env.FOO} ) can access these values.

TODO

https://issues.jenkins.io/browse/JENKINS-40574


Parameterized Build

If the pipeline was configured at creation time with "This project is parameterized", it designates a "parameterized build", meaning that the build UI exposes the "Build with Parameters" option. Alternatively, if "This project is parameterized" is not selected, the build UI will expose "Build Now" option, which does not give the choice of parameters.

Each parameter has a name and a value, which depends on the parameter type. The parameter name is case-sensitive. A default value and a description can be specified when the parameter is declared. Each parameter should have a unique name. Spaces are not permitted in parameter names.

The parameters are available as environment variables, and they can be accessed from the Jenkinsfile, Groovy code, shell, etc.

"Build with Parameters" gives the user the option to specify values for each defined parameter. If they choose not to do anything, the build will start with the "Default Value". A new value specified in the UI will override the default specified in Jenkinsfile. If the build is started automatically, the "Default Value" is used, unless the build triggering function provides the corresponding values, as follows:

build(
  job: "IntegrationTesting",
  parameters: [
    string(name: 'branch', value: serverSha),
    string(name: 'branchName', value: branch)
  ] + artifacts.keySet().sort().collect({ name ->
          echo "name: ${name}, value: ${artifacts[name]['artifact']}"
          string(name: name, value: artifacts[name]['artifact'])
    }),
    quietPeriod: 0,
    wait: true,
    propagate: true
)

For a parameterized build, once the Jenkinsfile is committed to the repository, the Jenkins server monitoring the branch will automatically update the UI based on the new Jenkinsfile, making the parameter available in the UI. For more details see Relationship between the Pipeline UI and Jenkinsfile Parameters below. As such, a parameter enables the pipeline to prompt the user for a piece of information to be passed into the build.

Relationship Between the Pipeline UI and Jenkinsfile Parameters

If the pipeline was configured to accept parameters using "Build with Parameters" option, once a parameter is defined in Jenkinsfile, and the Jenkinsfile committed to the repository, the pipeline that is initialized by an SCM script (this applies to both simple pipelines and multi-branch pipelines) automatically updates the pipeline UI for that branch, so the parameter become available in "Build with Parameters" associated with the branch.


Jenkins does not know about the new parameters until it retrieves the Jenkinsfile, parses it and runs it, and the only way to do that is to run a build, which will be based on the old Jenkinsfile. When something is changed in the Jenkinsfile, the next build will run with the "old" Jenkinsfile, but pick up and process the new Jenkinsfile for the build after that.

Declarative Pipeline Paramenter Declaration

Declarative pipelines support parameters by default, with the parameters directive.

Scripted Pipeline Paramenter Declaration

properties([

  parameters([

    string(
        name: 'POD_MEMORY_LIMIT_Gi',
        defaultValue: '8', 
        description: 'The pod\'s cgroups memory limit, in Gi')

  ])
])

Multi-line description:

properties([
  parameters([
    string(
        name: 'something'
        description: """
    This is a 
    multi-line
    description
    """.stripIndent()
  ])
])

Parameters Types

https://jenkins.io/doc/pipeline/steps/pipeline-input-step/

String

properties([
  parameters([
    string(
        name: 'COLOR',
        defaultValue: 'blue', 
        description: 'Some color')
  ])
])

Multi-Line String Parameter

File Parameter

Accessing Parameters

In Jenkinsfile

The name-value pairs are exported as environment variables when the build starts, allowing subsequent parts of the build configuration, such as build steps, to access those values using the following syntax:

${POD_MEMORY_LIMIT_Gi}

The parameters are also accessible as members of the params variable throughout the Jenkinsfile (params.paramName is equivalent with params.get(paramName)):

echo "pod memory limit: ${params.POD_MEMORY_LIMIT_Gi}"

Jenkinsfile Groovy code can only access parameters using the params.paramName form and not as environment variables.

In Groovy Code

TODO, so far the parameters were passed into Groovy code as arguments of constructors and function calls form Jenkinsfile.

In Shell