I'm setting a Jenkins pipeline Jenkinsfile and I'd like to check if a booleanparameter is set.
Here's the relevant portion of the file:
node ("master") {
stage 'Setup' (
[[$class: 'BooleanParameterValue', name: 'BUILD_SNAPSHOT', value: 'Boolean.valueOf(BUILD_SNAPSHOT)']],
As I understand, that is the way to access the booleanparameter but I'm not sure how to state the IF statement itself.
I was thinking about doing something like:
if(BooleanParameterValue['BUILD_SNAPSHOT']){...
What is the correct way to write this statement please?
Jenkins scripted Pipeline when statement You can use the declarative pipeline system to define the Pipeline; otherwise, you can use the if-else statement instead of the when statement.
Steps on How to Create a Boolean Parameter in JenkinsStep 1: Click on Configure. Step 2: Then look for “This project is parameterized” checkbox. Then check the checkbox.
Following the same old Jenkins Parameter tutorial to navigate to the project first. Step 1: Click on Configure. Step 2: Then look for “This project is parameterized” checkbox. Then check the checkbox. Step 3: Click on Add Parameter and select boolean parameter from the dropdown as shown in the image below:
Note: The parameters specified in the Jenkinsfile will appear in the job only after the first run. Your first job run will fail as you will not be able to provide the parameter value through the job. You can access a parameter in any stage of a pipeline. Accessing parameters in stages is pretty straightforward. You just have to use params.
So the answer is, no, right now it is not possible, but, it should be fairly simple to implement this as a step and add to a plugin. Show activity on this post. I think that this is the most correct/best practice way about using if/else or control logic within your Jenkins Declarative pipeline.
Thi parameter type returns a set of parameters returned by the groovy script. For example, an environment parameter that lists dev, stage, and prod values. You can also return values from third party APIs as parameters. One such example is dynamically showing folders from a Github repo in the Jenkins parameters.
A boolean parameter is accessible to your pipeline script in 3 ways:
As a bare parameter, e.g: isFoo
From the env
map, e.g: env.isFoo
From the params
map, e.g: params.isFoo
If you access isFoo
using 1) or 2) it will have a String value (of either "true" or "false").
If you access isFoo
using 3) it will have a Boolean value.
So the least confusing way (IMO) to test the isFoo
parameter in your script is like this:
if (params.isFoo) {
....
}
Alternatively you can test it like this:
if (isFoo.toBoolean()) {
....
}
or
if (env.isFoo.toBoolean()) {
....
}
the toBoolean()
is required to convert the "true"
String to a boolean true
and the "false"
String to a boolean false
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With