Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run stage only if previous stage was successful in Jenkins Scripted 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?

like image 832
buffcat Avatar asked Dec 05 '18 18:12

buffcat


People also ask

How do I stop Jenkins pipeline if stage fails?

Alternatively you can call error(String message) step to stop the pipeline and set its status to FAILED . For example, if your stage 1 calls error(msg) step like: stage("Stage 1") { steps { script { error "This pipeline stops here!" } } }

Which of the following tasks can be performed by a stage in scripted pipeline?

A Jenkins Scripted Pipeline is a sequence of stages to perform CI/CD-related tasks that can be specified as code, enabling you to develop a pipeline script and add it to your code repository so you can version it.


1 Answers

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
    }
}
like image 166
grolegor Avatar answered Sep 21 '22 05:09

grolegor