Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send "back to normal" notifications in Jenkins Declarative Pipeline?

I'm trying to convert an existing Jenkins Pipeline to the new Declarative Pipeline and I was wondering how to handle correctly mail notifications ?

I'm currently using this code:

node {
   try {

      ...

      currentBuild.result = 'SUCCESS'
   } catch (any) {
       currentBuild.result = 'FAILURE'
       throw any
   } finally {
       step([$class: 'Mailer',
           notifyEveryUnstableBuild: true,
           recipients: "[email protected]",
           sendToIndividuals: true])
   }
}

It works well, but I don't see how to use the new declarative syntax for this. I think something could be done by using post() and the different notifications, but I don't know exactly how. I've tried this:

post {
    always {
        step([$class: 'Mailer',
            notifyEveryUnstableBuild: true,
            recipients: "[email protected]",
            sendToIndividuals: true])
    }
}

But the problem is that it does not send any "Back to normal" mail.

How can I used the Mailer plugin in a Jenkins declarative pipeline in order to send "Back to normal" mails ?

Should use again a try/catch around all declarative syntax ?

like image 968
Baptiste Wicht Avatar asked Jun 02 '17 12:06

Baptiste Wicht


2 Answers

Problem is that in the post section of declarative the currentBuild.result is not set to SUCCESS. FAILURE and ABORTED is set though. So the behaviour here seems to be inconsistent at the moment.

I've improved my answer from How to get same Mailer behaviour for Jenkins pipeline to handle this case better:

pipeline {
  agent any
  stages {
      stage('test') {
        steps {
            echo 'some steps'        
            // error("Throw exception for testing purpose..")
        }
      }
  }
  post {
      always {
          script {
              if (currentBuild.result == null) {
                  currentBuild.result = 'SUCCESS'    
              }
          }    
          step([$class: 'Mailer',
            notifyEveryUnstableBuild: true,
            recipients: "[email protected]",
            sendToIndividuals: true])
      }
  }
}
like image 139
Philip Avatar answered Sep 30 '22 16:09

Philip


This can be done a lot simpler now by using the fixed post-condition (Documentation).

Here's a quick example I wrote up in my sandbox pipeline project.

pipeline{
    agent {
        label 'Build'
    }
    stages{
        stage('Build'){
            steps{
                script{
                    echo "Building..."
                }
            }
        }
    }
    post{
        success {
            echo "Success"
        }
        failure {
            echo "Failure"
        }
        fixed {
            echo "Back to normal"
        }
    }
}
like image 24
German Avatar answered Sep 30 '22 18:09

German