#
Conditional stage in Jenkins pipeline
This tutorial explains how we can execute a stage in Jenkins when a condition occurs. Also, inside a stage we can have a condition for doing or not a task.
First of all I want to highlight that a prerequisite for this article is Create Declarative Pipeline tutorial.
Now we modify the Jenkinsfile
in GitHub. The new Jenkinsfile
will be like this:
def var1 = 0
pipeline {
agent any
stages {
stage('Stage 1') {
when {
expression {var1 == 1}
}
steps {
echo 'Stage 1 ...'
}
}
stage('Stage 2') {
when {
expression {var1 != 1}
}
steps {
echo 'Stage 2 ...'
}
}
stage('Stage 3') {
steps {
echo 'within myStage'
script {
if (var1 == 1) {
echo 'Stage 3/A'
} else {
echo 'Stage 3/B'
}
}
}
}
}
}
When we run the pipeline, we will get:
Also, the Console Output has the following content:
Stage "Stage 1" skipped due to when conditional
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Stage 2)
[Pipeline] echo
Stage 2 ...
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Stage 3)
[Pipeline] echo
within myStage
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Stage 3/B
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Conclusions
- We can change the pipeline execution at the stage level and inside the stage as well
when
is the key word which allow or not the execution of a stage- in a stage we can run a scripts which can have conditionals inside