如何在 Jenkinsfile 中对失败的构建执行操作 [英] How to perform actions for failed builds in Jenkinsfile

查看:21
本文介绍了如何在 Jenkinsfile 中对失败的构建执行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to perform cleanup (or rollback) if the build in Jenkinsfile failed?

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

I would like to inform our Atlassian Stash instance that the build failed (by doing a curl at the correct URL).

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

Basically it would be a post step when build status is set to fail.

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

Should I use try {} catch ()? If so, what exception type should I catch?

推荐答案

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

I'm currently also searching for a solution to this problem. So far the best I could come up with is to create a wrapper function that runs the pipeline code in a try catch block. If you also want to notify on success you can store the Exception in a variable and move the notification code to a finally block. Also note that you have to rethrow the exception so Jenkins considers the build as failed. Maybe some reader finds a more elegant approach to this problem.

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

这篇关于如何在 Jenkinsfile 中对失败的构建执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆