Reputation: 2197
How do I mark a stage as skipped when using scripted pipeline. I have no problem skipping a stage in declarative pipeline. I just set
when {
expression {<some boolean expression>}
}
And if the expression is evaluate to false that stage is skipped.
The problem is that if you try to do this with scrippted pipeline you get:
java.lang.NoSuchMethodError: No such DSL method 'when' found among steps
error message. This is because the DSL of declarative pipeline is not the same as scripted pipeline So, how can it be done?
Upvotes: 20
Views: 32384
Reputation: 636
I created a shared library utility:
import org.jenkinsci.plugins.pipeline.modeldefinition.Utils as jUtils
/*
Mark stage as skipped:
sources:
*) https://github.com/jenkinsci/pipeline-model-definition-plugin/blob/master/pipeline-model-definition/src/main/groovy/org/jenkinsci/plugins/pipeline/modeldefinition/Utils.groovy
*) https://javadoc.jenkins.io/plugin/pipeline-model-definition/org/jenkinsci/plugins/pipeline/modeldefinition/Utils.html
*/
static void markStageSkipped(String stageName, Boolean conditionalSkip = true){
if(conditionalSkip){
jUtils.markStageSkippedForConditional(stageName)
} else{
jUtils.markStageSkippedForFailure(stageName)
}
}
Then:
node(''){
...
stage("Deploy"){
if(!doDeploy){
echo "Skipping deployment..."
Utils.markStageSkipped(env.STAGE_NAME)
} else{
//deployment logic goes here
}
}
}
Upvotes: 0
Reputation: 2197
Solving this issue takes a little bit of hacking... (don't worry, nothing fancy)
The way to do this is by using Jenkins' module that can be found here.
So to mark a stage as skipped you need to call static method markStageSkippedForConditional passing the name of the stage you are skipping.
Lets say you have a stage named "mystage". and you want to skip it and mark it as "skipped". Your code should look something like:
import org.jenkinsci.plugins.pipeline.modeldefinition.Utils
node() {
stage('a'){
echo 'stage 1'
}
stage('mystage'){
if(true){
echo 'skipping stage...'
Utils.markStageSkippedForConditional('mystage')
}else{
echo 'This stage may be skipped'
}
}
stage('b'){
echo 'stage 2'
}
}
If you're using a version of Jenkins older than mid 2019, you must uncheck Use Groovy Sandbox
checkbox, since the Utils method was not yet whitelisted for external use.
Upvotes: 38
Reputation: 123
In declarative pipeline you can use:
stage('deploy') {
when { <some boolean expression> }
......
}
In Scripted pipeline you can use:
if(<some boolean expression>) {
stage('deploy') {
......
}
}
both above works fine. i tested
Upvotes: -2
Reputation: 37580
You can find an implementation (in the form of a shared pipeline step) in comquent/imperative-when on GitHub.
This allows to access the method Utils.markStageSkippedForConditional
that you found yourself in a nice way, like the following:
stage('Zero') {
when(BRANCH_NAME != 'master') {
echo 'Performing steps of stage Zero'
}
}
Upvotes: 18