How to Use Options in Jenkins Pipeline for Better Control
In Jenkins Pipeline, use the
options block inside your pipeline or stage to set build behaviors like timeouts, retry counts, or timestamps. These options help control how your pipeline runs and handles failures.Syntax
The options block is placed inside the pipeline or stage block. It contains one or more option directives that control pipeline behavior.
Each option is a function call with parameters, for example, timeout(time: 10, unit: 'MINUTES').
groovy
pipeline {
agent any
options {
timeout(time: 10, unit: 'MINUTES')
retry(3)
timestamps()
}
stages {
stage('Example') {
steps {
echo 'Running with options'
}
}
}
}Example
This example shows a Jenkins Pipeline using options to set a timeout of 5 minutes, retry the build 2 times on failure, and add timestamps to the console output.
groovy
pipeline {
agent any
options {
timeout(time: 5, unit: 'MINUTES')
retry(2)
timestamps()
}
stages {
stage('Build') {
steps {
echo 'Starting build...'
// Simulate a step that might fail
script {
if (env.BUILD_NUMBER.toInteger() % 2 == 0) {
error 'Simulated failure'
}
}
echo 'Build succeeded'
}
}
}
}Output
[Pipeline] echo
Starting build...
[Pipeline] script
[Pipeline] error
ERROR: Simulated failure
[Pipeline] }
[Pipeline] // retry
[Pipeline] echo
Starting build...
[Pipeline] echo
Build succeeded
Common Pitfalls
- Placing
optionsoutside thepipelineorstageblock causes syntax errors. - Using unsupported options or misspelling option names will fail the pipeline.
- Setting conflicting options (like multiple
timeoutdirectives) can cause unexpected behavior.
groovy
pipeline {
agent any
// Wrong: options block outside pipeline
}
// Correct usage:
pipeline {
agent any
options {
timeout(time: 10, unit: 'MINUTES')
}
stages {
stage('Test') {
steps {
echo 'Test running'
}
}
}
}Quick Reference
| Option | Description | Example |
|---|---|---|
| timeout | Stops build if it runs longer than specified time | timeout(time: 15, unit: 'MINUTES') |
| retry | Retries the build specified number of times on failure | retry(3) |
| timestamps | Adds timestamps to console output | timestamps() |
| disableConcurrentBuilds | Prevents concurrent builds of the same job | disableConcurrentBuilds() |
| buildDiscarder | Controls how many builds to keep | buildDiscarder(logRotator(numToKeepStr: '10')) |
Key Takeaways
Use the
options block inside pipeline or stage to control build behavior.Common options include
timeout, retry, and timestamps.Place
options correctly to avoid syntax errors.Options help make pipelines more reliable and easier to manage.
Refer to Jenkins documentation for a full list of available options.