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

Article ID:217591038
1 minute readKnowledge base

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());
This article is part of our Knowledge Base and is provided for guidance-based purposes only. The solutions or workarounds described here are not officially supported by CloudBees and may not be applicable in all environments. Use at your own discretion, and test changes in a safe environment before applying them to production systems.