11

I am looking for the cleanest way to exit a declarative Jenkins pipeline, with a success status. While exiting with an error is very neat using error step , I couldn't find any equal way to exit with success code. E.G:

stage('Should Continue?') {
  when {
    expression {skipBuild == true }
  }
  steps {
    echo ("Skiped Build")
    setBuildStatus("Build complete", "SUCCESS");
    // here how can I abort with sucess code?
    // Error Would have been:
    // error("Error Message")

  }
}
stage('Build') {
  steps {
    echo "my build..."
  }
}

For Example with a scripted build, I could achieve it with the following code:

if (shouldSkip == true) {
  echo ("'ci skip' spotted in all git commits. Aborting.")
  currentBuild.result = 'SUCCESS'
  return
}

While I am aware of the ability to add a script step to my declarative pipieline, I was hoping to find a cleaner way.

Another approach could be throwing an error and catch it somewhere down the line, but again it quite messy.

Is there a cleaner way?

mkobit
  • 43,979
  • 12
  • 156
  • 150
BarakD
  • 538
  • 8
  • 18
  • Declarative languages do not really work this way. This is more imperative languages (as you noted, scripted does this). – Matthew Schuchard Nov 19 '17 at 16:50
  • Why is adding a script step not clean? – cantSleepNow Feb 11 '18 at 20:44
  • 5
    A `return` will only exit that stage, but it does not exit the entire pipeline. I am not aware of a way to exit the whole pipeline. – Tri Nguyen Jun 21 '18 at 15:56
  • 5
    The fact that there's no simple way of doing this really looks like an oversight. Having to a "skip" condition to every step in a pipeline with 10+ steps, just to cover this case is a headache. – user3656550 May 15 '20 at 17:05

1 Answers1

7

A solution that worked for me was to create a stage with sub-stages and put the check in the top level stage.

    stage('Run if expression ') {
        when {
            expression { skipBuild != true }
        }
        stages {
            stage('Hello') {
                steps {
                    echo "Hello there"
                }
            }
        }
    }

So I put all the stages that I want to continue inside this stage. And everything else outside of it. In your case you would put all your build stages inside the stage with when check.

Gerold Broser
  • 14,080
  • 5
  • 48
  • 107
Ivan
  • 16,536
  • 6
  • 23
  • 36