Declarative pipeline when condition in post

Using a GitHub Repository and the Pipeline plugin I have something along these lines:

pipeline {
  agent any
  stages {
    stage('Build') {
      steps {
        sh '''
          make
        '''
      }
    }
  }
  post {
    always {
      sh '''
        make clean
      '''
    }
    success {
      script {
        if (env.BRANCH_NAME == 'master') {
          emailext (
            to: '[email protected]',
            subject: "${env.JOB_NAME} #${env.BUILD_NUMBER} master is fine",
            body: "The master build is happy.\n\nConsole: ${env.BUILD_URL}.\n\n",
            attachLog: true,
          )
        } else if (env.BRANCH_NAME.startsWith('PR')) {
          // also send email to tell people their PR status
        } else {
          // this is some other branch
        } 
      }
    }     
  }
}

And that way, notifications can be sent based on the type of branch being built. See the pipeline model definition and also the global variable reference available on your server at http://your-jenkins-ip:8080/pipeline-syntax/globals#env for details.


In the documentation of declarative pipelines, it's mentioned that you can't use when in the post block. when is allowed only inside a stage directive. So what you can do is test the conditions using an if in a script:

post {
success {
  script {
    if (env.BRANCH_NAME == 'master')
        currentBuild.result = 'SUCCESS'
  }
 }
// failure block
}

Tags:

Jenkins