我怎么知道詹金斯管道的哪个阶段失败了

How do I know which stage of jenkins pipeline has failed

在我的 Jenkins 管道中,我通常使用 post 声明函数来向我发送电子邮件,以防管道出现故障。

post 函数的简单语法如下:

post {
    failure {
        mail to: 'team@example.com',
             subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
             body: "Something is wrong with ${env.BUILD_URL}"
    }
}

在上面的电子邮件中,我还想提及管道的哪个阶段(假设管道有 5 到 6 个阶段)发生故障。我怎样才能做到这一点?非常感谢任何帮助。

上述要求的扩展是向用户提供(已失败阶段的)实际错误日志,并将其作为失败通知电子邮件的一部分。

想法是,当用户收到来自 jenkins 的失败通知时,他应该知道管道的哪个阶段失败以及错误日志。

提前致谢。

有一个名为 env.STAGE_NAME 的变量可供您使用。但是,在您的情况下,您可能需要将阶段名称存储在不同的变量中,因为当您在 post 阶段获得 env.STAGE_NAME 时,结果将是 Declarative: Post Actions。相反,您需要将阶段名称存储在所有阶段的变量中。因此,一旦一个阶段失败 - Jenkins 将不会继续下一阶段,因此您将拥有 "failed" 阶段名称。

这是一个例子:

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

可能有更好的方法,但我目前还没有找到。

关于日志 - 从 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 开始并通过电子邮件发送整个构建日志文件:

emailext attachLog: true, body: '', compressLog: true, subject: 'Build failed.', to: 'somebody@somewhere.com'