groovyjenkins-workflowjenkins-pipeline

How to perform actions for failed builds in Jenkinsfile


Is there a way to perform cleanup (or rollback) if the build in Jenkinsfile failed?

I would like to inform our Atlassian Stash instance that the build failed (by doing a curl at the correct URL).

Basically it would be a post step when build status is set to fail.

Should I use try {} catch ()? If so, what exception type should I catch?


Solution

  • I'm currently also searching for a solution to this problem. So far the best I could come up with is to create a wrapper function that runs the pipeline code in a try catch block. If you also want to notify on success you can store the Exception in a variable and move the notification code to a finally block. Also note that you have to rethrow the exception so Jenkins considers the build as failed. Maybe some reader finds a more elegant approach to this problem.

    pipeline('linux') {
        stage 'Pull'
        stage 'Deploy'
        echo "Deploying"
        throw new FileNotFoundException("Nothing to pull")
        // ... 
    }
    
     def pipeline(String label, Closure body) {
         node(label) {
            wrap([$class: 'TimestamperBuildWrapper']) {
                try {
                    body.call()
                } catch (Exception e) {
                    emailext subject: "${env.JOB_NAME} - Build # ${env.BUILD_NUMBER} - FAILURE (${e.message})!", to: "me@me.com",body: "..."
                    throw e; // rethrow so the build is considered failed                        
                } 
            }
        }
    }