0

I'm currently facing the problem that I want to set a stage, in this case stage 2, to "UNSTABLE" if some steps fail and to "FAILED" if more then e.g. 60% of the steps are failing.

My Jenkins file currently looks like this:

pipeline {
    agent any
    stages {
        stage("stage1") {
            steps {
                echo "prepare some stuff"
            }
        }
        stage("stage2") {
            steps {
                parallel(
                        "step1": {
                            sh 'false'
                        },
                        "step2": {
                            sh 'true'
                        },
                        "step3": {
                            sh 'false'
                        }
                )
            }
        }
        stage('stage3') {
            steps {
                echo "do some other stuff"
            }
        }
    }
}
Alan H
  • 3,021
  • 4
  • 25
  • 24
Robert
  • 29
  • 1
  • 7

1 Answers1

4

Try catch

If you want the second steps runs no mather what happen with first step, you must catch any error on first step. You could do that using a try catch block.

According to this answer : https://stackoverflow.com/a/43303039/3957754 , in declarative pipeline you can't just use try directly. You have to wrap arbitrary groovy code in the script step

stage('Maven Install') {
   steps {
       script {

           echo "Step 1"

           try {
               sh "mvn clean install"
           } catch (Exception err) {
               //increment error count
           } finally {
               //do something
           }
       }

       script {

           echo "Step 2"

           try {
               sh "mvn clean install"
           } catch (Exception err) {
               //increment error count
           } finally {
               //do something
           }
       }       
   }
}

Mark stage as UNSTABLE/FAILURE

According to official documentation https://jenkins.io/doc/pipeline/tour/post/ you could use always block:

always {
    echo 'One way or another, I have finished'
    //put here your final logic
}

This block will be executed when all previous stages are been e, so here you can apply some logic using the error count and set a state to entire build :

  • currentBuild.result = 'SUCCESS'
  • currentBuild.result = 'FAILURE'
  • etc
JRichardsz
  • 14,356
  • 6
  • 59
  • 94