Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send notifications in Jenkins pipeline when build recovers?

I want to send notifications from my Jenkins pipeline build when the job recovers. Meaning when the current build is successful and the last build was erroneous (failed, aborted etc).

I know how to send notifications. I think my question boils down to how to check the status of the previous build, but I might be mistaken.

I have tried "currentBuild.rawBuild.getPreviousBuild()?.getResult()", but got exception "org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper getRawBuild". If I turn sandbox off, it should work. Would it be possible with the sandbox?

like image 717
Joosep Simm Avatar asked Mar 03 '17 11:03

Joosep Simm


People also ask

How do I enable email notifications in Jenkins pipeline?

To configure the SMTP for Email extension plugging, Goto manage Jenkins > configure systems > lookout for Extended E-mail Notification. Click on advance options and fill in the details as per the below screenshot. Save the Jenkins pipeline and click on the build now button.

How can Jenkins notify in case of a build failure?

Let's go back to main jenkins job queue and select the job which require notification. Select “Configure”. Select “Add post-build action” and Click “E-Mail Notification”. Enter your recipients mail address and select first option “Send e-mail for every unstable build”.


4 Answers

I've found another working solution, which doesn't require you to manually keep track of your build result. Although, it requires use of a script element :(

pipeline {
  agent any
  post {
    success {
      script {
        if (currentBuild.getPreviousBuild() && 
            currentBuild.getPreviousBuild().getResult().toString() != "SUCCESS") {
          echo 'Build is back to normal!'
        }
      }
    }
  }
}
like image 100
Kolky Avatar answered Oct 19 '22 18:10

Kolky


Interesting question. You can do it in Jenkins declarative pipeline using the 'changed' part of a post{} section. But you will need to set currentBuild.result to SUCCESS or FAILURE in the job and check it in the post section. There does not seem to be an easy way to get the current build status (fail, success etc) as far as Jenkins is concerned without tracking it in your pipeline - unless I have missed something subtle. Here is an example, you would send the notification in the changed section where it checks for SUCCESS:

pipeline {
    agent any

    parameters {
        string(name: 'FAIL',     defaultValue: 'false', description: 'Whether to fail')
    }

    stages {
        stage('Test') {

            steps {

                script {

                    if(params.FAIL == 'true') {
                        echo "This build will fail"
                        currentBuild.result = 'FAILURE'
                        error("Build has failed")
                    }
                    else {
                        echo "This build is a success"
                        currentBuild.result = 'SUCCESS'
                    }

                }
            }
        }
    }

    post {
        always  {
            echo "Build completed. currentBuild.result = ${currentBuild.result}"
        }

        changed {
            echo 'Build result changed'

            script {
                if(currentBuild.result == 'SUCCESS') {
                    echo 'Build has changed to SUCCESS status'
                }
            }
        }

        failure {
            echo 'Build failed'
        }

        success {
            echo 'Build was a success'
        }
        unstable {
            echo 'Build has gone unstable'
        }
    }
}

--Bill

like image 43
macg33zr Avatar answered Oct 19 '22 20:10

macg33zr


similar to answer by @Kolky, this would be the snippet for "Scripted pipeline", where you use " node{ stage1... stage2... etc }":

    stage('Email') {
        if (currentBuild.getPreviousBuild().getResult().toString() != "SUCCESS") {
            echo 'Build is back to normal!'
            stage('Send build recovered email') {
                mail body: 'My build back to successful',
//                    from: '', replyTo: '',
                        subject: 'My build back to successful',
                        to: '[email protected]'
            }

        }
    }
like image 26
Alex Avatar answered Oct 19 '22 20:10

Alex


Alternatively, you could move your script logic outside of the pipeline (ideally - to Jenkins shared pipeline library to be re-usable & keep the pipeline clean) so you wouldn't need the script block:

def sendNotification(buildStatus) {
  if (buildStatus != 'SUCCESS') {
    // Do nothing - only interested when status becomes GREEN
    return
  }

  mattermostSend "${env.JOB_NAME} has recovered! (<${env.BUILD_URL}|See the build>)"
}

pipeline {
  ...

  post {
    changed {
      sendNotification(currentBuild.currentResult)
    }
  }
}
like image 23
Jonas Masalskis Avatar answered Oct 19 '22 18:10

Jonas Masalskis