How to Iterate Through the Last Successful Builds in Pipeline Job?

Issue

Is there a way to get all the builds since the lastSuccessfulBuild in a Pipeline?

Environment

  • CloudBees Jenkins Platform
  • Jenkins

Resolution

This can be accomplished using the currentBuild and use the getPreviousBuild() linkage recursively. The following retrieves all the passed build since the lastSuccessfulBuild chronologically and add them to an array.

passedBuilds = []
def lastSuccessfullBuild(build) {
    if(build != null && build.result != 'FAILURE') {
        //Recurse now to handle in chronological order
        lastSuccessfullBuild(build.getPreviousBuild());
        //Add the build to the array
        passedBuilds.add(build);
    }
 }
 lastSuccessfullBuild(currentBuild.getPreviousBuild());

Have more questions?

2 Comments

  • 2
    Avatar
    Vaclave Vaclave

    It may be useful to do:

    build.result.toString().equals("SUCCESS")

    rather then:

    build.result != 'FAILURE'

    because the build.result field is a hudson.model.Result so it won't ever be equal to a String.

  • 0
    Avatar
    Richard Scott

    changing the double quotes on  build.result.toString().equals("SUCCESS")

    To

    build.result.toString().equals('SUCCESS')

    filtered the SUCCESS string on my pipe line jobs 

     

    Edited by Richard Scott
Please sign in to leave a comment.