Wubinator Wubinator - 4 months ago 44
Groovy Question

Jenkins boolean parameter is always true in groovy

I have a Jenkins job that calls a groovy script and the groovy script uses Jenkins parameters to do it's work. I can retrieve all the parameters without a problem except for a boolean parameter. The boolean parameter is a checkbox in Jenkins

unselected boolean parameter

I read the jenkins parameter into Groovy as follows:

boolean libraryBranch = config.get('library_branch_feature');


Now when I print the 'libraryBranch' variable

out.println "-- Library branch feature?: " + libraryBranch.toString();


I get the following printed line:


-- Library branch feature ?: true


So it doesn't matter if the boolean Jenkins parameter is selected or not I always have a boolean value 'true' in Groovy. All other (string) parameters inside the same job are read without a problem.

Can someone help me with this issue?

EDIT

Ok I've decided to try and retrieve the code in a couple of other ways and tyring to find a good solution:

Boolean libraryBranch = build.buildVariableResolver.resolve("library_branch_feature");
String libraryBranchString = build.buildVariableResolver.resolve("library_branch_feature").toString();
Boolean libraryBranchStringAsBoolean = build.buildVariableResolver.resolve("library_branch_feature") as Boolean;


The above variables are then printed:

out.println "-- Library branch feature?: " + libraryBranch;
out.println "-- Library branch feature to String: " + libraryBranch.toString();
out.println "-- Library branch feature to String: " + libraryBranch.toString();
out.println "-- Library branch feature as String: " + libraryBranchString;
out.println "-- Library branch feature String as Boolean: " + libraryBranchStringAsBoolean;


The output of the above prints are posted below:

-- Library branch feature?: true
-- Library branch feature to String: true
-- Library branch feature to String: true
-- Library branch feature as String: false
-- Library branch feature String as Boolean: true


So the only way thus far to have the boolean value read correctly as a false is by not turning it into a boolean at all but just reading it as a string and use it as a string.

I would rather use it as a boolean though so any suggestions on the matter is still appreciated.

Answer

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();