Jenkins boolean parameter is always true in groovy
Just out of curiosity, I tried the following:
Set the variable 'testmode' as a boolean in the pipeline setup. Start the job, with testmode set false (unchecked). In the pipeline script, run the following code immediately upon entry:
testmode=testmode.toBoolean()
if (testmode==false) { print "testmode tests true"}else{print "testmode tests false"}
you will see the result 'testmode tests false'.
To verify my claim that the 'boolean' variable testmode is ACTUALLY a string when it comes in, I tried:
testmode=testmode.toBoolean()
testmode=testmode.toBoolean()
and it blew up on the 2nd 'toBoolean'. I'll spare you the error message...
So, I claim that testmode comes in as the string "false" instead of as a boolean (whether because of promotion, demotion, forcing, whatever).
So, if its a boolean parameter, and you really wanted to treat it like a boolean and not have to say 'if (booleanvar=="true")', then convert it to a boolean as above and you're done.
I encountered the same problem with reading java Properties - retrieved boolean values are always true. So, say I have a settings
file with property debugging=false
. This test will fail:
class ConfigurationTest extends GroovyTestCase {
void testProcessConfiguration() {
Properties properties=new Properties()
FileReader fileReader=new FileReader('settings')
properties.load(fileReader)
boolean debug=properties.getOrDefault('debugging',false)
assert !debug
fileReader.close()
}
}
But if you make it properties.getOrDefault('debugging',false).toString().toBoolean()
it will return correct value. Probably this is because of coercion?
The question and the answers are a bit dated. The modern method to
consume a boolean parameter is to use the params.
global values. params
properly exposes Boolean parameters such that the following both work and
require no string/boolean conversions.
if (params.library_branch_feature) {
// truth logic here
}
// or
if (params.library_branch_feature != false) {
// truth logic here
}
From the Pipeline Syntax for params.:
Exposes all parameters defined in the build as a read-only map with variously typed values. Example:
if (params.BOOLEAN_PARAM_NAME) {doSomething()} or to supply a nontrivial default value:
if (params.getOrDefault('BOOLEAN_PARAM_NAME', true)) {doSomething()}
NOTE: It may not make sense that a boolean parameter can have NO value, but '.getOrDefault()' is useful to set default values for string parameters.
The answer is to read the Jenkins parameter as String and then convert it to a boolean using the method .toBoolean(); So my libraryBranch is now set as follows:
boolean libraryBranch = build.buildVariableResolver.resolve("library_branch_feature").toString().toBoolean();