We are using the Script Pipeline syntax for our Jenkinsfile
which has a lot of stage defined to build and deploy our code. We have a use case w
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 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. :)
I would use environmental variables for skipping stages.
stage("Release"){
steps{
// Release procedure
}
when {
allOf{
branch 'release'
not{
environment name: 'JENKINS_SKIP_RELEASE', value: 'TRUE'
}
}
}
}
In my specific way of working the whole pipeline is a variable in a shared library So I tweaked it to check for an specific variable.
def call(body) {
// Execute the body and get parameters back.
def params = [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = params
body()
if (params.skip_release){
env.JENKINS_SKIP_RELEASE = 'TRUE'
}
[...]
Then all my Jenkinsfile
looks like a bunch of parameters.
@Library('shared') _
myGeneralizedPipeline {
skip_release = true
//Other parameters comes in this body
}
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)
})
}