Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins declarative pipeline conditional post action

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 ?

like image 382
Mikael Gibert Avatar asked Aug 02 '17 09:08

Mikael Gibert


People also ask

Can I mix declarative and scripted pipeline?

Yes you can only if you want to have external function inside step block.

What is conditional step in Jenkins?

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.

What is difference between declarative pipeline and script based pipeline?

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.


1 Answers

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.

like image 177
Jonas Masalskis Avatar answered Dec 01 '22 17:12

Jonas Masalskis