Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkinsfile declarative syntax for conditional post-build step

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.

  • https://jenkins.io/doc/book/pipeline/syntax/#when
  • https://jenkins.io/doc/pipeline/tour/post/
like image 336
augurar Avatar asked Oct 30 '18 21:10

augurar


People also ask

What is declarative pipeline syntax?

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 */ }

Is Jenkinsfile declarative?

A Jenkinsfile can be written using two types of syntax - Declarative and Scripted.

Which syntax does the declarative pipeline follow?

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.


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

like image 173
John Avatar answered Sep 28 '22 07:09

John