How to write properly an if statement in regards to a BooleanParameter in Jenkins pipeline Jenkinsfile?

The answer is actually way simpler than that ! According to the pipeline documention, if you define a boolean parameter isFoo you can access it in your Groovy with just its name, so your script would actually look like :

node {
   stage 'Setup'
   echo "${isFoo}"   // Usage inside a string
   if(isFoo) {       // Very simple "if" usage
       echo "Param isFoo is true"
       ...
   }
}

And by the way, you probably should'nt call your parameter BUILD_SNAPSHOT but maybe buildSnapshot or isBuildSnapshot because it is a parameter and not a constant.


A boolean parameter is accessible to your pipeline script in 3 ways:

  1. As a bare parameter, e.g: isFoo

  2. From the env map, e.g: env.isFoo

  3. 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.


simply doing if(isFoo){...} that will not guarantee it working :) To be safe, use if(isFoo.toString()=='true'){ ... }