用于条件后生成步骤的Jenkinsfile声明式语法

aug*_*rar 4 jenkins jenkins-pipeline jenkins-declarative-pipeline

我有一个Jenkinsfile用于这样的多分支管道:

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

我只想在master分支上发送失败电子邮件。有没有办法使邮件步骤成为条件邮件?根据文档,when伪指令只能在内使用stage

Joh*_*ohn 6

就像您注意到的那样,它仅在舞台内起作用。在发布条件内只能使用有效的步骤。您仍然可以在脚本块内部使用脚本化语法,并且脚本块是有效步骤。因此,您应该能够在脚本块中使用if来获得所需的行为。

...
  post {
    failure {
      script {
        if (env.BRANCH_NAME == 'master') {
          ... # your code here
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

参见JENKINS-52689