Search code examples
jenkinsjenkins-pipelinejenkins-pluginsjenkins-job-dsljenkins-cli

post action of jenkinsFile Stage get previous stage status instead of the current one



I'm having the following issue:
I have 2 stages on my pipeline and on stage 1 I got failure (expected) then the stage 2 is called (expected) and do what it needs to do and return success.
However on my post step of the stage 2 instead of it goes to success it goes to failure. Does anyone knows how to bypass this?
stage('stage 1') {
    step {
        //failure
    }
}
stage('stage 2') {
    step {
        //success
    }
    post {
        success {
            echo 'I succeeded!'
        }
        unstable {
            echo 'I am unstable :/'
        }
        failure {
            echo 'I failed :('
        }
        changed {
            echo 'Things were different before...'
        }
    }
}

Solution

  • I ended up in this issue, and I suspect you were doing something like what I was doing (trying to catch an error in a build step):

    pipeline {
        agent any
        stages {
            stage('stage 1') {
                steps {
                    catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
                        build 'job-which-fail'
                    }
                }
            }
            stage('stage 2') {
                steps { 
                    sh 'exit 0'
                }
                post {
                    success {
                        echo 'success stage 2'
                    }
                    failure {
                        echo 'failure stage 2'
                    }
                }
            }
        }
    }
    

    This does not work and trigger the behavior that you described. However, this is intended, according to this comment. The proper way to achieve such thing is by using build with propagate: false. I ended up with:

    pipeline {
        agent any
        stages {
            stage('stage 1') {
                steps {
                    catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
                        script {
                            def myBuild = build(job: 'job-which-fail', propagate: false)
                            def myResult = "${myBuild.getResult()}"
                            if (myResult != 'SUCCESS') {
                                error "Build failed with result ${myResult}"
                            }
                        }
                    }
                }
            }
            stage('stage 2') {
                steps { 
                    sh 'exit 0'
                }
                post {
                    success {
                        echo 'success stage 2'
                    }
                    failure {
                        echo 'failure stage 2'
                    }
                }
            }
        }
    }