Jenkinsfile - Conditional stage execution in the Script Pipeline syntax
Per the comments on JENKINS-47286, it doesn't sound like adding when
support to Scripted Pipeline will happen. As a potential workaround, there is a shared library implementing the when
statement for scripted pipelines: https://github.com/comquent/imperative-when
I also disliked the idea of having a redundant if{} block inside my stage{}. I solved this by overwriting the stage as follows
def stage(name, execute, block) {
return stage(name, execute ? block : {echo "skipped stage $name"})
}
now you can disable a stage as follows
stage('Full Build', false) {
...
}
Update You could also mark stage skipped using below def
import org.jenkinsci.plugins.pipeline.modeldefinition.Utils
def stage(name, execute, block) {
return stage(name, execute ? block : {
echo "skipped stage $name"
Utils.markStageSkippedForConditional(STAGE_NAME)
})
}
I don't use scripted pipelines, but I'm pretty sure that's the way you'd do it (enclosing the conditional stages in an if
).
If you want it to act a bit more like declarative, you could put if
statements inside each stage instead. That way the stages would still be visualized. This may or may not be desirable when they didn't actually do anything.
I think switching to declarative will be the only way to get the skipped stages displayed differently in the blue ocean UI (they look different when they are skipped due to a when
clause), but you actually have the smallest code with your current solution. It doesn't seem hacky to me, but that sort of thing can be subjective. :)