Issue
I have a Jenkinsfile
which will be triggered by GitLab (using Webhooks).
I want to skip the whole Jenkinsfile
's execution if a particular condition is not met.
One way to do this is to apply the same condition on each stage
pipeline {
agent any
stages {
stage ('Stage 1') {
when {
expression {
//Expression
}
}
//do something
}
stage ('Stage 2') {
when {
expression {
//Expression
}
}
//do something
}
stage ('Stage 3') {
when {
expression {
//Expression
}
}
//do something
}
.
.
.
.
}
}
But this seems weird as I want the same condition to be applied for all the stages.
Can we apply similar condition over stages
itself ? Like this?
pipeline {
agent any
stages {
when {
expression {
//Expression
}
}
stage ('Stage 1') {
//do something
}
stage ('Stage 2') {
//do something
}
stage ('Stage 3') {
//do something
}
.
.
.
.
}
}
Solution
"Can we apply 'when' condition in 'stages' of a Jenkinsfile?" No.
Per Pipeline Syntax, when is only allowed within a stage.
The when directive allows the Pipeline to determine whether the stage should be executed depending on the given condition. The when directive must contain at least one condition. If the when directive contains more than one condition, all the child conditions must return true for the stage to execute. This is the same as if the child conditions were nested in an allOf condition (see the examples below). If an anyOf condition is used, note that the condition skips remaining tests as soon as the first "true" condition is found.
More complex conditional structures can be built using the nesting conditions: not, allOf, or anyOf. Nesting conditions may be nested to any arbitrary depth.
Can you simply have a first stage with the expression and fail/abort the pipeline if met?
Answered By - Ian W
Answer Checked By - Mildred Charles (JavaFixing Admin)