How to add email notification in jenkins if the build is failed - jenkins

I need to add email notification in jenkins for both freestyle and pipeline job if the build is failed

reg. Email-ext plugin
In pipeline job you can use post build actions / try catch with proper step - ref. to mail
pipeline {
agent any
stages {
stage('Test') {
steps {
sh 'echo "Fail!"; exit 1'
}
}
}
post {
always {
echo 'This will always run'
}
success {
echo 'This will run only if successful'
}
failure {
echo 'This will run only if failed'
}
unstable {
echo 'This will run only if the run was marked as unstable'
}
changed {
echo 'This will run only if the state of the Pipeline has changed'
echo 'For example, if the Pipeline was previously failing but is now successful'
}
}
}
or try-catch (scripted way)
try{
//code to handle
} catch (e) {
emailext (
from: 'sender#domain.com',
to: 'recepient#domain.com',
subject: "job failed- ${env.JOB_NAME}, Build #${env.BUILD_NUMBER}, FAILED",
attachLog: true,
body: """
Foooooo text
For current build refer to: ${env.BUILD_URL}
job: ${env.JOB_NAME}
build number: #${env.BUILD_NUMBER}
With ERROR:
${e.message}
For full log refer to
${env.BUILD_URL}
"""
)
throw e
}

Post Build Actions > Email Notification
Part of the Mailer plugin.

Related

Jenkins Build Log for every stage in Pipeline

Everyone, I am looking for build log for every stage that I have executed in the pipeline.
Below is my build stage.
Stage('Build'){
bat 'mvn -f workspace/pom.xml clean install'
emailtext body: '', subect:'build is done', to:'xxxx'
}
I have configured emailing in the stage but it is just giving the normal email. But our requirement is we need to get a complete build. Could you please let me know what can be done to get complete build log.
You need mainly two things.
First, to log somehow which stages have run already. Then, you can use post actions to notify, whatever the way you want to do it.
This is just one way.
If you need to log the stages in error you need to catch the steps and set the right build log. Otherwise you can just skip the try catches, and send the completed stages.
def buildLog = "Stages Completed:"
def failedStageLog = ""
pipeline {
agent any
stages {
stage('Hello 1') {
steps {
script {
try{ //catch errors
echo 'Hello World 1'
}catch(e){ //define your message
failedStageLog = "Hello 1"
error("Failing pipeline") //force to exit on failed stage caught
}
buildLog = buildLog+" Hello 1"
}
}
}
stage('Hello 2') {
steps {
script{
try{ //catch errors
echo 'Hello World 2'
}catch(e){ //define your message
failedStageLog = "Hello 2"
error("Failing pipeline") //force to exit on failed stage caught
}
buildLog = buildLog+", Hello 2"
}
}
}
}
post{
success{
println buildLog // parse and send email
}
unsuccessful{
println "Error on pipeline stage: $failedStageLog. $buildLog " // parse and send email
}
}
}
Output example
Success Message: Pipeline status: SUCESS. Stages Completed: Hello 1, Hello 2
Error Message: Pipeline status: UNSUCESSFUL. Failed stage: Hello 2. Stages Completed: Hello 1

Not receiving Failure email from Jenkins

Using Jenkins now, this is my post build Pipeline:
pipeline {
agent any
stages {
stage('Stage 1') {
steps {
echo 'Hello this is stage 1'
}
}
stage('Stage 2') {
steps {
echo 'Still here? Well this is stage 2'
}
}
stage('Stage 3') {
steps {
echo 'Almost there ... stage 3'
}
}
stage('Stage 4 - Python') {
steps {
bat 'py atom_python_test.py'
}
}
stage('Stage 5 - Compile C++') {
steps {
catchError {
bat '''
cd C:\Program Files (x86)//Microsoft Visual Studio 12.0//VC
call vcvarsall
cd C://Users//praktikant3//Documents//Visual Studio 2013//Projects//FirstProjectBuiltOnJenkins//FirstProjectBuiltOnJenkins
dir
MSBuild.exe
echo 'Compile Stage successful'
'''
}
}
}
stage('Stage 6 - Build C++') {
steps {
bat '''
cd C://Program Files (x86)//Microsoft Visual Studio 12.0//VC
call vcvarsall
cd C://Users//praktikant3//Documents//Visual Studio 2013//Projects//FirstProjectBuiltOnJenkins//FirstProjectBuiltOnJenkins
dir
MSBuild.exe
'''
}
}
}
post {
success {
mail to: 'SomeEMAIL#company.com',
subject: "Succeeding Pipeline: ${currentBuild.fullDisplayName}",
body: "All is good with ${env.BUILD_URL}"
}
failure {
mail to: 'SomeEMAIL#company.com',
subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
body: "Something is wrong with ${env.BUILD_URL}"
}
}
}
The build C++ part works because I the syntax is correct, however in previous attempt I had the directory change using "\" which was not working. I added a "Compile stage" using catchError and one of the cd with a "\" to see if I get notification of failure. From my understanding:
"You should wrap every step that can potentially fail into a catchError function. What this does is:
If an error occurs...
... set build.result to FAILURE...
... andcontinue the build "
but when I intentionally left the back slash the pipeline failed and stopped and the post block did not execute.

Jenkins Pipeline Groovy Script: Use `mail` in Jenkinsfile

I'm trying to send an email when a Pipeline build on Jenkins fails. An example can be found here: https://github.com/jenkinsci/pipeline-examples/blob/master/jenkinsfile-examples/nodejs-build-test-deploy-docker-notify/Jenkinsfile
My concrete groovy script looks as follows:
#!groovy
node('') {
def env = ["JAVA_HOME=${tool 'jdk1.8.0_131'}", "PATH+MAVEN=${tool 'maven_3.1.1'}/bin:${env.JAVA_HOME}/bin", "PATH+GRADLE=${tool 'gradle_4.1'}/bin:${env.JAVA_HOME}/bin" ]
def err = null
currentBuild.result = "SUCCESS"
try {
stage('errorStage') {
dir('error') {
git url: "unknown", branch: "master"
withEnv(env) {
sh "mvn -Pjenkins-build clean deploy"
}
}
}
} catch (caughtError) {
println "caught error :" + caughtError
err = caughtError
currentBuild.result = "FAILURE"
mail (body:
"Pipeline error: ${err}\nFix me.",
from: 'jenkins#x.com',
subject: 'Pipeline build failed',
to: 'recipient#x.com')
} finally {
/* Must re-throw exception to propagate error */
if (err) {
throw err
}
}
}
Actually, nothing ever happens, although the exception is being caught correctly and the build fails. Is there anything required to be able to use mail?! Maybe another Jenkins plugin or something?
I was able to fix it myself by using emailext plugin on Jenkins instead of mail. The code looks as follows now:
emailext body: "Pipeline error: ${err}\nPlease go to ${BUILD_URL} and verify the build",
recipientProviders: [[$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider']],
subject: "'${JOB_NAME}' (${BUILD_NUMBER}) failed",
to: '...'

Chained multiple pipeline based on 'post' jenkins block

I'm beginner to Jenkins. I have code pipeline structure like this
Repo1 -> Repo2 -> Repo3 -> Deploy
I already created such hierarchy via GUI but I want to create it via pipeline as code.I want to create chain of pipelines where I clone different repos and perform tests on it and then continue to another repo based on current pipeline post result.
This is my jenkinsfile - (psuedo code like as it gives me error to build)
pipeline {
agent any
stages {
stage('Build Repo1') {
steps {
sh 'echo "repo1 build!"'
}
}
stage('Test Repo1') {
steps {
sh 'echo "repo success!"'
}
}
}
post {
success {
pipeline {
agent any
stages {
stage('Build Repo2') {
steps {
sh 'echo "build repo2!"'
}
}
stage('Test Repo2') {
steps {
sh 'echo "test repo2!"'
}
}
}
post {
success {
# continue to generate pipeline for repo3
echo 'This will always run'
}
failure {
echo 'This will run only if failed'
}
}
}
}
failure {
echo 'This will run only if failed'
}
unstable {
echo 'This will run only if the run was marked as unstable'
}
changed {
echo 'This will run only if the state of the Pipeline has changed'
echo 'For example, if the Pipeline was previously failing but is now successful'
}
}
}
Please help!

Set the build name and description from a Jenkins Declarative Pipeline

I would like to set the build name and description from a Jenkins Declarative Pipeline, but can't find the proper way of doing it. I tried using an environment bracket after the pipeline, using a node bracket in an agent bracket, etc. I always get syntax error.
The last version of my Jenkinsfile goes like so:
pipeline {
stages {
stage("Build") {
steps {
echo "Building application..."
bat "%ANT_HOME%/bin/ant.bat clean compile"
currentBuild.name = "MY_VERSION_NUMBER"
currentBuild.description = "MY_PROJECT MY_VERSION_NUMBER"
}
}
stage("Unit Tests") {
steps {
echo "Testing (JUnit)..."
echo "Testing (pitest)..."
bat "%ANT_HOME%/bin/ant.bat run-unit-tests"
}
}
stage("Functional Test") {
steps {
echo "Selenium..."
}
}
stage("Performance Test") {
steps {
echo "JMeter.."
}
}
stage("Quality Analysis") {
steps {
echo "Running SonarQube..."
bat "%ANT_HOME%/bin/ant.bat run-sonarqube-analysis"
}
}
stage("Security Assessment") {
steps {
echo "ZAP..."
}
}
stage("Approval") {
steps {
echo "Approval by a CS03"
}
}
stage("Deploy") {
steps {
echo "Deploying..."
}
}
}
post {
always {
junit '/test/reports/*.xml'
}
failure {
emailext attachLog: true, body: '', compressLog: true, recipientProviders: [[$class: 'CulpritsRecipientProvider'], [$class: 'DevelopersRecipientProvider']], subject: '[JENKINS] MY_PROJECT build failed', to: '...recipients...'
}
success {
emailext attachLog: false, body: '', compressLog: false, recipientProviders: [[$class: 'DevelopersRecipientProvider']], subject: '[JENKINS] MY_PROJECT build succeeded', to: '...recipients...'
}
}
}
Error is:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 11: Expected a step # line 11, column 5.
currentBuild.name = "MY_VERSION_NUMBER"
^
WorkflowScript: 12: Expected a step # line 12, column 5.
currentBuild.description = "MY_PROJECT MY_VERSION_NUMBER"
^
Ideally, I'd like to be able to read MY_PROJECT and MY_VERSION_NUMBER from the build.properties file, or from the Jenkins build log. Any guidance about that requirement would be appreciated as well.
UPDATE
Based on the answer I had below, the following worked:
stage("Build") {
steps {
echo "Building application..."
bat "%ANT_HOME%/bin/ant.bat clean compile"
script {
def props = readProperties file: 'build.properties'
currentBuild.displayName = "v" + props['application.version']
}
}
Now the build version is automatically set during the pipeline by reading the build.properties file.
I think this will do what you want. I was able to do it inside a script block:
pipeline {
stages {
stage("Build"){
steps {
script {
currentBuild.displayName = "The name."
currentBuild.description = "The best description."
}
... do whatever.
}
}
}
}
The script is kind of an escape hatch to get out of a declarative pipeline. There is probably a declarative way to do it but i couldn't find it. And one more note. I think you want currentBuild.displayName instead of currentBuild.name In the documentation for Jenkins globals I didn't see a name property under currentBuild.
If you want to set build name to a job from a parameter, you can use
currentBuild.displayName = "${nameOfYourParameter}".
Make sure you use double quotes instead of single quotes.
Job Configuration
Build job with parameter
Build History
REFERENCE: How to set build name in Pipeline job?

Resources