Jenkins – Run stage only if previous stage was successful in Jenkins Scripted Pipeline

Jenkinsjenkins-pipeline

I am trying to run conditional steps in a Jenkins scripted pipeline, however I am not sure how to only run a step if a previous step was successful. For instance, in the following I only want to run the 'Push Artifacts' stage if the 'Test' stage was successful:

node ('docker2') {

    stage ('Build') {
        // build application
    }

    stage ('Test') {
        // run tests
    }

    stage ('Push Artifacts') { 
        if (Tests Were Successful) {  
            // push to artifactory
        }
    }
}

I know that declarative pipelines allow you to use 'post' conditions, but my understanding of declarative vs. scripted pipelines in Jenkins is that scripted pipelines offer more flexibility. Is there a way to run stages based on other stages' success in a scripted pipeline?

Best Answer

There is no concept of success step or failed step in jenkins pipeline. There is only status of your build (success, failed, unstable, etc.)

You have two ways to resolve your problem:

First. You can fail your pipeline if test are failed (using 'error' jenkins step). For example:

stage('Build') {
    // build application
}

stage('Test') {
    def testResult = ... // run command executing tests
    if (testResult == 'Failed') {
        error "test failed"
    }
}

stage('Push Artifacts') {
    //push artifacts
}

Or if your command propagates error when tests are failed (like 'mvn test') then you can write like this:

stage('Build') {
    // build application
}

stage('Test') {
    sh 'mvn test'
}

stage('Push Artifacts') {

}

In these cases your pipeline will be failed when tests are failed. And no stage after 'Test' stage will be executed.

Second. If you want to run only some steps, depending on the step you performed you should write test result into variable. And you can analyse value of that variable before running steps. For example:

stage('Build') {
    // build application
}

boolean testPassed = true
stage('Test') {
    try{
        sh 'mvn test'
    }catch (Exception e){
        testPassed = false
    }
}

stage('Push Artifacts') {
    if(testPassed){
        //push to artifactory
    }
}