How to Use Boolean Parameter in Jenkins Pipeline
In Jenkins, you can use a
booleanParam to add a true/false option for your build. Define it in the pipeline with parameters { booleanParam(name: 'FLAG', defaultValue: true, description: 'Enable feature?') } and access it in your script as params.FLAG.Syntax
The booleanParam is used inside the parameters block in a Jenkins pipeline to create a checkbox input. It has three parts:
- name: The variable name to use in the pipeline.
- defaultValue: The initial true or false value.
- description: A short text explaining the parameter.
groovy
pipeline {
agent any
parameters {
booleanParam(name: 'FLAG', defaultValue: true, description: 'Enable feature?')
}
stages {
stage('Example') {
steps {
script {
if (params.FLAG) {
echo 'Feature is enabled'
} else {
echo 'Feature is disabled'
}
}
}
}
}
}Example
This example shows a Jenkins pipeline with a boolean parameter named DEPLOY. The pipeline prints a message depending on whether DEPLOY is true or false.
groovy
pipeline {
agent any
parameters {
booleanParam(name: 'DEPLOY', defaultValue: false, description: 'Deploy to production?')
}
stages {
stage('Check Deploy') {
steps {
script {
if (params.DEPLOY) {
echo 'Deploying to production...'
} else {
echo 'Skipping deployment.'
}
}
}
}
}
}Output
[Pipeline] echo
Deploying to production...
Common Pitfalls
Common mistakes when using boolean parameters include:
- Forgetting to define the parameter in the
parametersblock, causingparams.FLAGto be undefined. - Using string comparison instead of boolean checks, e.g.,
if (params.FLAG == 'true')instead ofif (params.FLAG). - Not providing a description, which can confuse users.
groovy
pipeline {
agent any
stages {
stage('Wrong Usage') {
steps {
script {
// This will fail because 'FLAG' is not defined
if (params.FLAG) {
echo 'This will error'
}
}
}
}
}
}
// Correct usage:
pipeline {
agent any
parameters {
booleanParam(name: 'FLAG', defaultValue: false, description: 'Enable feature?')
}
stages {
stage('Right Usage') {
steps {
script {
if (params.FLAG) {
echo 'Feature enabled'
} else {
echo 'Feature disabled'
}
}
}
}
}
}Quick Reference
| Property | Description | Example |
|---|---|---|
| name | Name of the boolean parameter | `booleanParam(name: 'FLAG', ...)` |
| defaultValue | Initial true or false value | `defaultValue: true` |
| description | Text shown to users | `description: 'Enable feature?'` |
| Access | Use in pipeline script | `if (params.FLAG) { ... }` |
Key Takeaways
Define boolean parameters inside the parameters block using booleanParam.
Access boolean parameters in the pipeline with params.PARAM_NAME as a true/false value.
Always provide a clear description for the parameter to help users.
Avoid comparing boolean parameters as strings; use direct boolean checks.
Missing parameter definitions cause errors when accessing params.