I have a Jenkinsfile for a multibranch pipeline like this:
pipeline {
agent any
stages {
// ...
}
post {
failure {
mail to: '[email protected]',
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
.
Declarative Pipeline is a relatively recent addition to Jenkins Pipeline which presents a more simplified and opinionated syntax on top of the Pipeline sub-systems. All valid Declarative Pipelines must be enclosed within a pipeline block, for example: pipeline { /* insert Declarative Pipeline here */ }
A Jenkinsfile can be written using two types of syntax - Declarative and Scripted.
The basic statements and expressions which are valid in Declarative Pipeline follow the same rules as Groovy's syntax with the following exceptions: The top-level of the Pipeline must be a block, specifically: pipeline { } . No semicolons as statement separators. Each statement has to be on its own line.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With