如何在Jenkinsfile中为失败的构建执行操作

Krz*_*soń 14 groovy jenkins-workflow jenkinsfile

如果Jenkinsfile中的构建失败,有没有办法执行清理(或回滚)?

我想通知我们的Atlassian Stash实例构建失败(通过curl在正确的URL处执行).

基本上,当构建状态设置为失败时,它将是一个后续步骤.

我应该用try {} catch ()吗?如果是这样,我应该捕获哪种异常类型?

ama*_*edo 20

从2017-02-03开始,Declarative Pipeline Syntax 1.0可用于实现此post build步骤功能.

它是构建管道的新语法,它使用预定义的结构扩展了Pipeline,并使用一些新步骤使用户能够定义代理,后期操作,环境设置,凭据和阶段.

以下是带有声明性语法的示例Jenkinsfile:

pipeline {
  agent  label:'has-docker', dockerfile: true
  environment {
    GIT_COMMITTER_NAME = "jenkins"
    GIT_COMMITTER_EMAIL = "jenkins@jenkins.io"
  }
  stages {
    stage("Build") {
      steps {
        sh 'mvn clean install -Dmaven.test.failure.ignore=true'
      }
    }
    stage("Archive"){
      steps {
        archive "*/target/**/*"
        junit '*/target/surefire-reports/*.xml'
      }
    }
  }
  post {
    always {
      deleteDir()
    }
    success {
      mail to:"me@example.com", subject:"SUCCESS: ${currentBuild.fullDisplayName}", body: "Yay, we passed."
    }
    failure {
      mail to:"me@example.com", subject:"FAILURE: ${currentBuild.fullDisplayName}", body: "Boo, we failed."
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

职位代码块就是处理该登记步骤行动

声明性管道语法参考在这里


Til*_*uhn 19

我目前也在寻找这个问题的解决方案.到目前为止,我能想到的最好的方法是创建一个在try catch块中运行管道代码的包装器函数.如果您还想通知成功,可以将Exception存储在变量中,并将通知代码移动到finally块.另请注意,您必须重新抛出异常,以便Jenkins认为构建失败.也许有些读者会发现这个问题更优雅.

pipeline('linux') {
    stage 'Pull'
    stage 'Deploy'
    echo "Deploying"
    throw new FileNotFoundException("Nothing to pull")
    // ... 
}

 def pipeline(String label, Closure body) {
     node(label) {
        wrap([$class: 'TimestamperBuildWrapper']) {
            try {
                body.call()
            } catch (Exception e) {
                emailext subject: "${env.JOB_NAME} - Build # ${env.BUILD_NUMBER} - FAILURE (${e.message})!", to: "me@me.com",body: "..."
                throw e; // rethrow so the build is considered failed                        
            } 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • `TimestamperBuildWrapper`的奖励积分,我不知道它存在 (3认同)