Jenkins is an open-source automation server that enables developers to build, test, and deploy their software. In this short tutorial, we'll show you how to send an email notification after Jenkins build fails. This is a very common scenario and for the sake of this example, we'll use a built-in Jenkins Mailer plugin. Sometimes is very handy to also send a Slack notification, where the Slack Notification Jenkins plugin is of great help.
Implementation
In this example, we'll build a simple demo pipeline where we'll call a health check route of Spring Boot application and in case that the returned HTTP status is not 200 or that service returned an error, we'll send an email to the list of email addresses.
Before we execute our first build using the following configuration, we should make sure that we configured the Mailer plugin in terms of server properties. It should be configured in the Manage Jenkins -> Configure System -> E-mail notification section. If you need any help in configuring this, check out Jenkins Mailer plugin official documentation.
1. We'll go to the Jenkins Dashboard, choose New Item from the top left corner, give it a name, and choose Pipeline for the item type.
2. In the Build Triggers section, let's check the Build periodically box and schedule this pipeline for every 15 minutes.
image
3. Let's write the pipeline script in the Pipeline section:
node {
try{
stage ('Health check') {
httpRequest ("10.10.10.10:8002/someservice/actuator/health")
}
}catch(e){
step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: "email1@gmail.com,email2@gmail.com", sendToIndividuals: true])
}
}
Notice that recipient mail addresses should be separated with a comma and that you should set notifyEveryUnstableBuild to true to stay regularly notified.
Here we are also using the httpRequest Jenkins plugin that is much handier than using, for example, curl.
Conclusion
In this quick and handy tutorial, we discussed you how to send an email notification after Jenkins build fails. We also showed one way of achieving this, using Jenkins pipelines.