Process Flow - Custom notification logic
Build Starts
Run Build Steps
Check Build Result
Send Success
End Notification
The build runs, then checks the result. Based on success, failure, or unstable, it sends a custom notification accordingly.
pipeline {
agent any
stages {
stage('Build') {
steps { echo 'Building...' }
}
}
post {
success { echo 'Notify: Build succeeded' }
failure { echo 'Notify: Build failed' }
unstable { echo 'Notify: Build unstable' }
}
}| Step | Build Stage | Build Result | Notification Logic | Notification Sent |
|---|---|---|---|---|
| 1 | Start Build | N/A | No notification yet | None |
| 2 | Run Build Steps | N/A | No notification yet | None |
| 3 | Check Result | Success | Trigger success notification | Notify: Build succeeded |
| 4 | End | Success | No further notifications | None |
| 5 | Restart Build | Failure | Trigger failure notification | Notify: Build failed |
| 6 | End | Failure | No further notifications | None |
| 7 | Restart Build | Unstable | Trigger unstable notification | Notify: Build unstable |
| 8 | End | Unstable | No further notifications | None |
| Variable | Start | After Step 3 | After Step 5 | After Step 7 | Final |
|---|---|---|---|---|---|
| buildResult | N/A | Success | Failure | Unstable | Unstable |
| notificationSent | None | Notify: Build succeeded | Notify: Build failed | Notify: Build unstable | Notify: Build unstable |
Jenkins pipeline uses 'post' section for notifications. Notifications depend on build result: success, failure, unstable. Only one notification sent after build finishes. Use 'success', 'failure', 'unstable' blocks in 'post' to customize. This ensures clear, condition-based alerts.
currentBuild.currentResult to get build status and compare with string 'FAILURE'.post {
failure {
script {
if (currentBuild.previousBuild?.result == 'SUCCESS') {
notify('Build failed after success')
}
}
}
}post.failure block runs only if current build failed. Inside, it checks if previous build result was 'SUCCESS'.notify is called with the message.post {
failure {
script {
if (currentBuild.previousBuild.result == 'SUCCESS') {
notify('Failed after success')
}
}
}
}currentBuild.previousBuild can be null if no previous build exists.result on null causes NullPointerException. Safe navigation operator ?. avoids this.Pass the test and this pattern moves unknown