Conditionals in a Declarative Pipeline Jenkinsfile
In this article I’ll show how to express conditionals — like if
, else
or switch
— in a Jenkinsfile using the declarative pipeline syntax.
Optional Stages (≅ if)
Generally it is possible to use Groovy’s conditionals in a declarative syntax, when we use a script
step.
So for example, if we only want a release to happen, if a certain boolean parameter RELEASE
is set, we code it like this:
But in that case, we end up with a stage that looks like it was successfully executed, but in fact it didn’t do anything.
The declarative way of expressing this is the when
directive, which will skip or execute a whole stage according to a condition.
And then evaluate its value in a when
directive on the release stage:
Nice. This code is even shorter and less indented. Jenkins will display the stage to be skipped or executed in the build overview, so we can find the last build that performed a release without having to check the logs.
Either A or B (≅ if/else)
Sometimes we want either one or another thing to happen. For example we have a mechanism to build a pre-release and another to build a final release.
So, here’s the version using script
with if
and else
:
Not too bad. This is short and still readable. However, to Jenkins this is one step and to find out what happened in hindsight is not easy as we’d need to check the logs on the executions.
We can get more declarative using two successive stages with when
, where the first when can only be true, if the second is false and vice versa.
This is a bit more code, but still reads alright and we get a much better understanding by looking at the graph.
But after all, both stages are doing the same thing (publishing) and it would be nicer to have them grouped by something more then just by name.
For this we can wrap both stages in a parallel
section:
Now, when we look at the pipeline graph, we get a nice overview, which way the build took.
One of Many (≅ switch)
In some cases, we not only want to chose one out of two, but out of many alternatives. E.g. we’d like to add a deploy stage but want to choose the target stage via parameter.
Again, we can fallback to script
and use switch
for this:
Again, this is quite short and well readable in the Jenkinsfile, but in the pipeline graph, it is hard to see, where the deployment went to.
But we can apply the same trick as before, only now we use a choice
parameter:
This is a lot more code, compared to the simple script
solution above, but the pipeline graph gets a lot more expressive.
Conclusion
Especially the later examples clearly show that declarative pipelines are not necessarily the best choice regarding the amount of (stupid) code. However, the resulting pipeline graphs show what happened very nicely.
Grouping alternative stages in parallel
makes the graphs even more expressive and also binds the repetitive code together.