I am using Jenkins declarative pipeline and want to perform some post build actions depending on the build status.
To be more precise, I want to send an email when the build status changed (from success to failure, or success to unstable, or failure to success).
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 ?
Yes you can only if you want to have external function inside step block.
Conditional step (single) This build step allows you to select any build step and define a condition to control whether the step should be executed.
Basically, declarative and scripted pipelines differ in terms of the programmatic approach. One uses a declarative programming model and the second uses an imperative programming mode. Declarative pipelines break down stages into multiple steps, while in scripted pipelines there is no need for this.
For writing conditions you can define your own methods.
For example, if you want to send an email only 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 would also want to put notifyStatusChangeViaEmail
method definiton in your shared pipeline library so that it could be re-used in other jobs/pipelines.
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