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?
First add a "Conditional steps (multiple)" build step. Choose "Regular expression match" for the "Run?" field. This will allow you to check if the changeset owner/author is the "jenkins" user. The "Expression" field is "^jenkins$", which is the name of the Plastic SCM user from whom we want to skip the builds.
Scripted and declarative pipelines follow the same goal and use the same pipeline sub-system under the hood. The major differences between them are flexibility and syntax. They're just two different tools for solving the same problem, thus, we can and should use them interchangeably.
Scripted vs declarative pipelines in Jenkins – differences One uses a declarative programming model and the second uses an imperative programming mode. Declarative pipelines break down stages into multiple steps, while in scripted pipelines there is no need for this.
Solving this issue takes a little bit of hacking... (dont 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'
}
}
Note that you MUST uncheck Use Groovy Sandbox
checkbox, since the Utils method is restricted.
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'
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With