Jenkinsfile declarative syntax for conditional post-build step

Viewed 2781

I have a Jenkinsfile for a multibranch pipeline like this:

pipeline {
    agent any
    stages {
        // ...
    }
    post { 
        failure { 
            mail to: 'team@example.com',
                 subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
                 body: "Something is wrong with ${env.BUILD_URL}"
        }
    }
}

I want to only send email for failures on the master branch. Is there a way to make the mail step conditional? Based on the documentation a when directive may only be used inside a stage.

1 Answers

like you've noted when only works inside a stage. And only valid steps can be used inside the post conditions. You can still use scripted syntax inside of a script block, and script blocks are a valid step. So you should be able to use if inside a script block to get the desired behavior.

...
  post {
    failure {
      script {
        if (env.BRANCH_NAME == 'master') {
          ... # your code here
        }
      }
    }
  }
}

see JENKINS-52689

Related