BarakD
BarakD

Reputation: 548

Clean way to exit declarative Jenkins pipeline as success?

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?

Upvotes: 11

Views: 10339

Answers (2)

Barel elbaz
Barel elbaz

Reputation: 646

import hudson.model.Result
import jenkins.model.CauseOfInterruption
import org.jenkinsci.plugins.workflow.steps.FlowInterruptedException

def haltBuildWithSuccess() {
    // Mark the current build as a success
    currentBuild.rawBuild.@result = Result.SUCCESS
    // Create a custom interruption cause
    def cause = new CauseOfInterruption.UserInterruption("Build halted programmatically with SUCCESS status")
    // Throw a FlowInterruptedException to halt the build
    throw new FlowInterruptedException(Result.SUCCESS, false, cause)
}

pipeline{
    agent any
    stages{
        stage("First"){
            steps{
                script{
                    haltBuildWithSuccess()

                }
            }
        }
        stage("won't be executed"){
            steps{
                echo "You will Never see it"
            }
        }
    }
}

Show it was marked as SUCCESS

Show extra badge in the build page

Upvotes: 1

Ivan
Ivan

Reputation: 16908

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.

Upvotes: 8

Related Questions