How do I know which stage of jenkins pipeline has failed

淺唱寂寞╮ 提交于 2020-02-18 08:10:30

问题


In my Jenkins pipelines I generally use post declarative function to send me an email incase the pipeline has failed.

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

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.

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.

Thanks in advance.


回答1:


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.

Here's an example:

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.

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'



来源:https://stackoverflow.com/questions/50411381/how-do-i-know-which-stage-of-jenkins-pipeline-has-failed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!