3

In a Jenkins scripted pipeline with the below structure, the return command will exit only the withEnv.

node{
    withEnv([...]){
        stage('1'){
        ...
        }

        stage('2'){
        .....
        }

        if( env.BRANCH_NAME != 'master' ) {
            currentBuild.result = 'SUCCESS'
            return
        }

        stage('3'){
        ...
        }       
    }

    stage('4'){
        withEnv([...]){
            ...
        }
    }

    stage('5'){
        ...
    }

    stage('6'){
    ...
    }
}

How can I stop the entire pipeline after stage2 with SUCCESS?

2 Answers 2

2

Just the way you can exit any stage prematurely by using return keyword, you can use the return keyword (outside of the stage) to exit the entire pipeline prematurely. You can re-use the currentBuild.result value outside of Stage 4. See below.

node{
    withEnv([...]){
        stage('1'){
        ...
        }

        stage('2'){
        .....
        }

        if( env.BRANCH_NAME != 'master' ) {
            currentBuild.result = 'SUCCESS'
            return
        }

        stage('3'){
        ...
        }       
    }

    stage('4'){
        withEnv([...]){
            ...
        }
    }

    if(currentBuild.result == 'SUCCESS') {
        return //this will exit the pipeline
    }

    stage('5'){
        ...
    }

    stage('6'){
    ...
    }
}
1

I think you are looking for error() function, this question has been answered somehow in: This question: Abort current build from pipeline in Jenkins

1
  • Does error() accept SUCCESS build status?
    – sgargel
    Commented Apr 1, 2019 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.