I have the following post
failure section:
post {
failure {
mail subject: "\u2639 ${env.JOB_NAME} (${env.BUILD_NUMBER}) has failed",
body: """Build ${env.BUILD_URL} is failing!
|Somebody should do something about that""",
to: "[email protected]",
replyTo: "[email protected]",
from: '[email protected]'
}
}
I would like to include the reasons why the build failed in the body of the error message.
How can I do that?
If not, is there a way to attach the build log file to the email?
In Jenkins, in the pipeline where failure occurred, in the pane, select the latest build, and click Console Output. On the Console Output page, check the logs to find the reason for the failure. If required, update the parameters in the deployment input configuration file.
Another approach is to use a catchError or at least a try/catch . Then, as in this answer, you can get the error message: String error = "${e}"; Regarding catchError, you would wrap every step that can potentially fail into a catchError function. If an error occurs, it will set build.
I don't know of a way to retrieve the failure reason automatically out of thin air.
However, you can use "post{ failure {" blocks in each phase to capture at least the phase in which it failed into a environment variable (e.g. env.FAILURE_REASON), and access that env var in the final (global scope) notification block.
For more granularity, you can reuse the same mechanism of the global env variable, but use try { } catch { } blocks to capture which specific step failed.
A generic example would be:
pipeline {
stages {
stage('Build') {
steps {
...
}
post {
failure {
script { env.FAILURE_STAGE = 'Build' }
}
}
}
stage('Deploy') {
steps {
...
}
post {
failure {
script { env.FAILURE_STAGE = 'Deploy' }
}
}
}
...
}
post {
failure {
mail subject: "\u2639 ${env.JOB_NAME} (${env.BUILD_NUMBER}) has failed",
body: """Build ${env.BUILD_URL} is failing in ${env.FAILURE_STAGE} stage!
|Somebody should do something about that""",
to: "[email protected]",
replyTo: "[email protected]",
from: '[email protected]'
}
}
}
Technically, you can even do some automated triage based on the failing stage and send a more targeted notification, or even create specific (e.g. Jira) tickets.
For attaching the console log to the email notification, you'd want to look at emailext and the 'attachLog: true' attribute
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With