Jenkins declarative pipeline conditional post action

Viewed 16259

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 ?

4 Answers

@psalvi was imho on the right track, but @mikael-gibert wanted in his comment to get notifications only for the first fixed build. Jenkins declarative pipelines can do that, see https://www.jenkins.io/doc/book/pipeline/syntax/#post. Here an example:

pipeline {
    // [...]
    post {
        always {
            script {
                // Examples of stuff you could do, based on some custom parameters and functions
                if (params.buildAndPublish && branchIsMain()) {
                    currentBuild.description = 'NOT promoted '
                }

                currentBuild.description = (currentBuild.description ?: '') + '[' + (params.customArtifactVersion ?: mavenArtifactVersion) + ']'

                if (params.buildAndPublish) {
                    // Tell Bitbucket about this build and its result
                    notifyBitbucket(credentialsId: config.credentialsId)

                    // Archive test results
                    junit(allowEmptyResults: true, testResults: "**/target/surefire-reports/**.xml,**/target/failsafe-reports/**.xml")
                }
            }
        }

        failure {
            emailext recipientProviders: [culprits(), requestor()],
                    subject: "[Jenkins] Build failed: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
                    body: "Hello,\n\nBuild failed: ${env.JOB_NAME} / ${env.BRANCH_NAME} #${env.BUILD_NUMBER}.\nDetails: ${env.BUILD_URL}\n\nJenkins"
        }

        fixed {
            emailext recipientProviders: [culprits(), requestor()],
                    subject: "[Jenkins] Build fixed: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
                    body: "Hello,\n\nBuild fixed: ${env.JOB_NAME} / ${env.BRANCH_NAME} #${env.BUILD_NUMBER}.\nDetails: ${env.BUILD_URL}\n\nJenkins"
        }
    }
}
Related