How can I add to a Jenkins pipeline an old-style post-build task which sends email when the build fails? I cannot find "Post-build actions" in the GUI for a pipeline. I know that I can wrap the entire build script try/catch, however, this seems ugly when the build script is large and continues to send emails even when the job was aborted manually. I would like to achieve the same functionality as with the previous email-ext
based post-build action.
try { // Do sth } catch(e) { emailext body: '$DEFAULT_CONTENT', recipientProviders: [ [$class: 'CulpritsRecipientProvider'], [$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider'] ], replyTo: '$DEFAULT_REPLYTO', subject: '$DEFAULT_SUBJECT', to: '$DEFAULT_RECIPIENTS' throw err }
This answer worked on my Jenkins ver. 2.96.
Jenkins pipeline email not sent on build failure - Stack Overflow
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 { mail bcc: '', body: "<b>Example</b><br>Project: ${env.JOB_NAME} <br>Build Number: ${env.BUILD_NUMBER} <br> URL de build: ${env.BUILD_URL}", cc: '', charset: 'UTF-8', from: '', mimeType: 'text/html', replyTo: '', subject: "ERROR CI: Project name -> ${env.JOB_NAME}", to: "[email protected]"; } 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' } } }
For taking action only when build status has changed you can use the post > changed block.
And for checking, what state the status has changed to you can use the script block in combination with checking the value of currentBuild.currentResult
property.
Like so:
pipeline { ... post { changed { script { if (currentBuild.currentResult == 'FAILURE') { // Other values: SUCCESS, UNSTABLE // Send an email only if the build status has changed from green/unstable to red emailext subject: '$DEFAULT_SUBJECT', body: '$DEFAULT_CONTENT', recipientProviders: [ [$class: 'CulpritsRecipientProvider'], [$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider'] ], replyTo: '$DEFAULT_REPLYTO', to: '$DEFAULT_RECIPIENTS' } } } } }
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