Jenkins conditional postulate contract
I am using Jenkins declarative pipeline and want to do some post build actions depending on build state.
To be more precise, I want to send an email when the build status changes (from success to failure or success to volatility or failure).
Here is my pipeline:
pipeline {
agent none
stages {
stage('test') {
agent any
steps {
sh './tests.sh'
}
}
}
post {
changed {
// Send different emails depending on build status
// Success -> anything else
// Anything else -> Success
}
}
}
Any idea?
source to share
You can define your own methods for recording conditions.
For example, if you only want to send an email when the build status changes:
def notifyStatusChangeViaEmail(buildStatus) {
def status
switch (buildStatus) {
case 'SUCCESS':
status = 'is now green again!'
break
case 'UNSTABLE':
status = 'has become unstable..'
break
case 'FAILURE':
status = 'has turned RED :('
break
}
emailext (
subject: "Job '${env.JOB_NAME}' ${status}",
body: "See ${env.BUILD_URL} for more details",
recipientProviders: [
[$class: 'DevelopersRecipientProvider'],
[$class: 'RequesterRecipientProvider']
]
)
}
pipeline {
...
post {
changed {
// Will trigger only when job status changes: GREEN -> RED, RED -> GREEN, etc
notifyStatusChangeViaEmail(currentBuild.currentResult)
}
}
}
Ideally, you will also want to install the method notifyStatusChangeViaEmail
in your shared pipeline library so that it can be reused in other jobs / pipelines.
source to share
Example: failure and volatility to success
if (currentBuild.result == 'SUCCESS') { if(hudson.model.Result.FAILURE.equals(currentBuild.rawBuild.getPreviousBuild()?.getResult()) || hudson.model.Result.UNSTABLE.equals(currentBuild.rawBuild.getPreviousBuild()?.getResult())) {
SEND MAIL()
}
}
to send email: https://jenkins.io/blog/2017/02/15/declarative-notifications/
source to share
Refer to this pipeline:
post {
success {
emailext (
subject: '${DEFAULT_SUBJECT}'+'SUCESSFUL',
body: '${DEFAULT_CONTENT}',
to: '${EMAIL_RECIPIENTS}'
);
slackSend (color: 'good', message: ":csp_operational: ${env.JOB_NAME} - #${env.BUILD_NUMBER} Success (<${env.BUILD_URL}|Open>)");
}
failure {
emailext (
subject: '${DEFAULT_SUBJECT}'+'FAILED!',
body: '${DEFAULT_CONTENT}',
to: '${EMAIL_RECIPIENTS}'
);
slackSend (color: 'danger', message: ":x: ${env.JOB_NAME} - #${env.BUILD_NUMBER} Failure (<${env.BUILD_URL}|Open>)");
}
}
You can set default email options using the advanced email module, Jenkins-> Configure Jenkins -> Advanced Email Configuration.
source to share