Issue
I am able to skip a stage using when condition successfully in jenkins declarative pipeline but i want to early abort the build if a set of conditions are not met. I tried putting when block at top level inside stages and outside stages as well but it gives syntax error saying "Expected stage" and "Undefined section when" respectively. Can anyone suggest how can i make it work ?
when {
anyOf {
not {
equals expected: true, actual: params.boolean_parameter
}
not{
equals expected: '', actual: params.string_parameter
}
}
}
Solution
In declarative pipelines the when
directive can be used only on stages.
To solve your issue you can just create a dummy stage for aborting the pipeline in case the condition is not meant, in that step you can use a regular when
directive and inside the steps of the stage just use the error
keyword for aborting the build with a relevant message (see the error documentation).
Something like:
pipeline {
agent any
stages {
stage('Validate Conditions') {
when {
anyOf {
not {
equals expected: true, actual: params.boolean_parameter
}
not{
equals expected: '', actual: params.string_parameter
}
}
}
steps {
error("Aborting the build because conditions are not met")
}
}
... // rest of pipeline
}
}
This way if conditions are not met the build will be aborted, however the post section will still be executed allowing you to send notifications and so if needed.
Answered By - Noam Helmer