Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 216
Krzysztof Krasoń Avatar asked Apr 25 '16 10:04

Krzysztof Krasoń


People also ask

How do I fix Jenkins build failure?

In Jenkins, in the pipeline where the failure occurred, in the navigation pane, click Rebuild. In the Rebuild page, select the ReRun check box , and click Rebuild.

How does Jenkins know when a build fails?

This plugin analyzes the causes of failed builds and presents the causes on the build page. It does this by using a knowledge base of build failure causes that is built up from scratch. Saving statistics about failure causes is also possible.

How do I ignore failed stage in Jenkins pipeline?

To ignore a failed step in declarative pipeline you basically have two options: Use script step and try-catch block (similar to previous proposition by R_K but in declarative style)


1 Answers

Since 2017-02-03, Declarative Pipeline Syntax 1.0 can be used to achieve this post build step functionality.

It is a new syntax for constructing Pipelines, that extends Pipeline with a pre-defined structure and some new steps that enable users to define agents, post actions, environment settings, credentials and stages.

Here is a sample Jenkinsfile with declarative syntax:

pipeline {
  agent  label:'has-docker', dockerfile: true
  environment {
    GIT_COMMITTER_NAME = "jenkins"
    GIT_COMMITTER_EMAIL = "[email protected]"
  }
  stages {
    stage("Build") {
      steps {
        sh 'mvn clean install -Dmaven.test.failure.ignore=true'
      }
    }
    stage("Archive"){
      steps {
        archive "*/target/**/*"
        junit '*/target/surefire-reports/*.xml'
      }
    }
  }
  post {
    always {
      deleteDir()
    }
    success {
      mail to:"[email protected]", subject:"SUCCESS: ${currentBuild.fullDisplayName}", body: "Yay, we passed."
    }
    failure {
      mail to:"[email protected]", subject:"FAILURE: ${currentBuild.fullDisplayName}", body: "Boo, we failed."
    }
  }
}

The post code block is what handles that post step action

Declarative Pipeline Syntax reference is here

like image 109
amarruedo Avatar answered Oct 02 '22 12:10

amarruedo