我怎么知道詹金斯管道的哪个阶段失败了 [英] How do I know which stage of jenkins pipeline has failed
问题描述
在我的Jenkins管道中,如果管道发生故障,我通常使用post
声明性函数向我发送电子邮件.
In my Jenkins pipelines I generally use post
declarative function to send me an email incase the pipeline has failed.
post
函数的简单语法如下:
A simple syntax of the post
function is as under:
post {
failure {
mail to: 'team@example.com',
subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
body: "Something is wrong with ${env.BUILD_URL}"
}
}
在以上电子邮件中,我还想提及管道的哪个阶段(假设管道有5到6个阶段)失败了.我怎样才能做到这一点?非常感谢您的帮助.
In the above email, I also want to mention which stage (lets say the pipeline has 5 to 6 stages) of the pipeline has failed. How can I do that? Any help is much appreciated.
对上述要求的扩展将是向用户提供(已失败阶段的)实际错误日志,并将其作为失败通知电子邮件的一部分.
An extension to the above requirement will be to provide the user with the actual error log (of the stage that has failed) also as a part of the failure notification email.
想法是,当用户收到jenkins的失败通知时,他应该知道管道的哪个阶段已失败以及错误日志.
Idea is, when a user receives a failure notification from jenkins, he should know which stage of the pipeline has failed along with the error log.
谢谢.
推荐答案
有一个名为env.STAGE_NAME
的变量可以使用.但是,根据您的情况,您可能需要将阶段名称存储在不同的变量中,因为当您在post
阶段获得env.STAGE_NAME
时,结果将是Declarative: Post Actions
.相反,您将需要在所有阶段中将阶段名称存储在变量中.因此,一旦某个阶段失败-詹金斯将不会继续进行下一个阶段,因此您将获得失败"的阶段名称.
There is a variable called env.STAGE_NAME
which you can use. However, in your case you will probably need to store the stage name in a different variable, because when you get the env.STAGE_NAME
in a post
stage the result will be Declarative: Post Actions
. Instead, you will need to store the stage name in a variable in all stages. So once a stage fails - Jenkins will not continue with the next stages and therefore you will have the "failed" stage name.
这是一个例子:
def FAILED_STAGE
pipeline {
agent { label "master" }
stages {
stage("Stage 1") {
steps {
script {
FAILED_STAGE=env.STAGE_NAME
echo "stage 1"
}
}
}
stage("Stage 2") {
steps {
script {
FAILED_STAGE=env.STAGE_NAME
echo "stage 2"
error "failed for some reason."
}
}
}
stage("Stage 3") {
steps {
script {
FAILED_STAGE=env.STAGE_NAME
echo "stage 3"
}
}
}
}
post {
failure {
echo "Failed stage name: ${FAILED_STAGE}"
}
}
}
也许有更好的方法,但是到目前为止我还没有发现.
There might be a better way to do it, but I haven't found it so far.
关于日志-从 JENKINS-40526 开始,您可以使用API并从那里获取日志文件,但是我不确定您可以从管道中获取所需的参数.另一种解决方案是使用 emailext 并通过电子邮件发送整个构建日志文件:
Regarding the logs - As of JENKINS-40526 you could possibly use the API and get the log file from there, but I am not sure you can get the parameters you need from within the pipeline. The other solution would be to use emailext and email the entire build log file:
emailext attachLog: true, body: '', compressLog: true, subject: 'Build failed.', to: 'somebody@somewhere.com'
这篇关于我怎么知道詹金斯管道的哪个阶段失败了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!