1

My first stage runs a shell script. Exit 0 marks it as success and exit 1 marks it as fail. How can I read this result into the pipeline and get the desired behavior:

  • Run stage 1
  • If stage 1 fails, don't run the remaining stages, but mark the whole pipeline as a success
  • If stage 1 succeeds, run the remaining stages
  • If any of them fail, mark the pipeline as a fail
  • If they all succeed, mark the pipeline as a success

I am doing this in a declarative pipeline, how can I enforce this behavior?

kiryakov
  • 145
  • 1
  • 7

1 Answers1

3

You can use something like this, catch the error and then change the currentBuild result :

pipeline {
    agent any
    stages {
        stage('Stage 1') {
            steps {
                script {
                    try {
                        // do something that fails
                        sh "exit 1"
                    } catch (Exception err) {
                        currentBuild.result = 'SUCCESS'
                    }
                }
            }
        }
        stage('Stage 2') {
            steps {
                echo "Stage 2"
            }
        }
        stage('Stage 3') {
            steps {
                echo "Stage 3"
            }
        }
    }
}

If you need to change a specific stage result, have a look to this link wich explain how to perform it.

fmdaboville
  • 1,394
  • 3
  • 15
  • 28
  • Yeah, this did it. I defined a boolean variable which was initially set to true and in the "catch" statement I set it to false. Then all the stages which needed to be skipped upon failure were marked with a "when {expression { } }" statement. Thank you! – kiryakov Sep 06 '21 at 11:40
  • Yes, that's fine to choose which stage needs to be skipped. – fmdaboville Sep 06 '21 at 11:47