How can I check previous build status in a Pipeline Script?

Issue

  • I want to be able to check on the status of my previous build in a pipeline script

Environment

  • CloudBees Jenkins Enterprise

Resolution

This would be what your pipeline script would look like:

if(!hudson.model.Result.SUCCESS.equals(currentBuild.rawBuild.getPreviousBuild()?.getResult())) {
  echo "last build failed"
}

This will check if the last build was a failure and then echo that the last build failed.

WARNING: Groovy sandbox has to be disabled for this to work because it is accessing the filesystem. RawBuild will also have to be whitelisted by the script security plugin once the Groovy sandbox is disabled.

Have more questions? Submit a request

3 Comments

  • 4
    Avatar
    Tomasz Szpinda

    why 

    currentBuild.rawBuild.getPreviousBuild()

    and not

    currentBuild.getPreviousBuild()

     

    second works and doesn't require whitelisting, or am I missing something?

  • 0
    Avatar
    Jerome Potma

    With the resolution above, I always get: "last build failed"

    I use the following code:

     
    if (currentBuild?.getPreviousBuild()?.result == 'FAILURE') {
    if (currentBuild.resultIsBetterOrEqualTo(
    currentBuild.getPreviousBuild().result)) {
    echo 'build has been fixed
    }
    }
     
     
    Edited by Jerome Potma
  • 0
    Avatar
    Craig Rodrigues

    If you are using a Pipeline script, take a look at the documentation of the currentBuild variable:

    https://ci.jenkins.io/pipeline-syntax/globals#currentBuild

    You can use the following Pipeline syntax:

     

    currentBuild.previousBuild.result

     

    currentBuild is of type RunWrapper, so you can use any whitelisted method on RunWrapper.

    I updated a lot of the Pipeline docs for currentBuild, because I had similar questions:

    https://github.com/jenkinsci/workflow-cps-plugin/pull/236
    https://github.com/jenkinsci/workflow-cps-plugin/pull/237

     

Please sign in to leave a comment.