Search code examples
jenkinsjenkins-pipelinejenkins-groovy

How to set the stage to unstable in scripted pipeline


In scripted pipeline i am trying to check the status of the downstream job . if the downstream job is failed i want to set the stage as unstable . i am trying the below code but it does not work

if (JOBRUN == "true" ){
    def downstream = build job: "/project/A/${env.BRANCH}", wait: true
    if (downstream.getResult() != 'SUCCESS') {
        unstable(message: "Downstream job result is ${downstream.result}")
    }
}

I have tried this option too

def downstream = build (job: "/project/A/${env.BRANCH}", wait: true).result
if (downstream.getResult() != 'SUCCESS') {
            unstable(message: "Downstream job result is ${downstream.result}")
        }


Solution

  • Jenkins automatically propagates the build result upwards so you don't have to specifically go and get the result from a method as the result is reflected in the status of the upstream build job. Instead, you can catch the error and change the result from your code. For example:

    script {
        try {
            build job: 'yourjob', wait: true
        } catch (err) {                                        
            unstable(message: "abc")
        }
    }    
    

    So in the above case, if yourjob fails, the entire stage that is triggering that job will also fail. However, since the failure is being caught, the error will be converted to unstable with whatever message you specify.