Jenkins管道故障原因在控制台的末尾,而不是在发生故障的步骤



我正在用Jenkinsfile创建一个多分支管道,如果一个步骤失败,我想在post步骤中发送的电子邮件中显示原因。

我可以获取日志很好,但我的问题是,失败原因打印在控制台日志的末尾,而不是在它发生的地方。

如果我创建一个自由式项目,那么错误信息将始终在控制台日志中出现,并且电子邮件将按预期工作。

我的Jenkinsfile看起来像这样:

pipeline {
agent any
parameters {
string(name: 'VERSION', defaultValue: '', description: 'version number to build')
}
stages {
stage("Check parameters") {
steps {
script {
if (VERSION == null || VERSION == '') {
error("Build failed because required parameter VERSION not set")
}
}
}
}
stage("Do something") {
...
}
stage("Rename successful build") {
steps {
script {
currentBuild.displayName = "v${VERSION}"
currentBuild.description = "Successful build for v${VERSION}"
}
}
}
}
post {
failure {
withFolderProperties {
echo "Recipients: ${env.MAIL_RECIPIENTS}"
script {
if (env.MAIL_RECIPIENTS) {
emailext (
to: env.MAIL_RECIPIENTS,
replyTo: '$DEFAULT_REPLYTO',
subject: '$DEFAULT_SUBJECT',
body: '$DEFAULT_CONTENT',
mimeType: 'text/html'
);
}
}
}
}
}
}

如果我在没有版本参数的情况下开始构建,这将生成以下控制台日志。

这只是一个例子,如果另一个阶段在某个点失败(我清理了一些[Pipeline]行),同样会继续存在:

[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Check parameters)
[Pipeline] script
[Pipeline] {
[Pipeline] error
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (build)
Stage "Do Something" skipped due to earlier failure(s)
...
Stage "Rename successful build" skipped due to earlier failure(s)
...
Sending email to: xxx
...
ERROR: Build failed because required parameter VERSION not set
Finished: FAILURE

电子邮件中缺少最后两行,因为它是在打印之前发送的;然而,为什么错误打印在日志的末尾,而不是在它发生的步骤?有一种方法,我可以配置这个?

我希望在日志中显示下一步之前打印错误。

您的期望可以很容易地通过Jenkins脚本化管道实现,但使用Jenkins声明式管道则有点困难。

但是在声明性管道中,如果你基于某些条件引发错误,你知道在构建结束时可能是什么错误,所以当你引发错误时,你可以在一个变量中获取错误字符串,并在失败阶段使用它。

InScripted Pipeline,它应该是这样的

def isItFail = false
def failureReason = ""
node {
try {
stage('check parameter') {
if (VERSION == null || VERSION == '') {
throw new RuntimeException("Version number should not be empty")                
}
}
stage('some other stage') {
.....
}
}catch(Exception e ) {
isItFail = true
failureReason = e.getMessage()
}finally {
if(isItFail) {
echo "Send An Email with this Text with Reason: ${failureReason}"
}
}
}

声明式管道,它应该是

def failReason = ""
pipeline {
agent any;
stages {
stage('check version') {
steps {
script {
script {
if (VERSION == null || VERSION == '') {
failReason = "Build failed because required parameter VERSION not set"
error(failReason)
}
}
}
}
}
stage('other stage') {
....
}
}
post {
failure {
echo "Send An Email with Reason : ${failReason}"
}
}
}

在声明性管道中,没有任何catch{}DSL,并且您不能在script{}DSL之外使用try..catch..finally,因此将失败原因文本带到管道末端有点困难

最新更新