How to retrieve build_id of latest successful build in Jenkins?

38,760

Solution 1

Yes, there is a way and it is pretty straightforward:

$ build_id=`wget -qO- jenkins_url/job/job_name/lastSuccessfulBuild/buildNumber`
$ echo $build_id
131 # that's my build number

Solution 2

I think the best solution is using groovy with zero dependencies.

node {
    script{
        def lastSuccessfulBuildID = 0
        def build = currentBuild.previousBuild
        while (build != null) {
            if (build.result == "SUCCESS")
            {
                lastSuccessfulBuildID = build.id as Integer
                break
            }
            build = build.previousBuild
        }
        println lastSuccessfulBuildID
    }
}

You do not need specify jenkins_url or job_name etc to get last successful build id. Then you could use it easily in all Jenkinsfile in repositories without useless configurations.

Tested on Jenkins v2.164.2

Solution 3

I find very useful querying permalinks file inside Jenkins workspace.

This allows you, to not only get the last successful build, but also other builds Jenkins considers relevant.

You can see it's content adding this line in Build section, in Execute Shell panel:

cat ../../jobs/$JOB_NAME/builds/permalinks

For example, in my case:

+ cat ../../jobs/$JOB_NAME/builds/permalinks
lastCompletedBuild 56
lastFailedBuild 56
lastStableBuild 51
lastSuccessfulBuild 51
lastUnstableBuild -1
lastUnsuccessfulBuild 56

From there, you would want to parse the number of the last successful build, or any other provided by permalinks, you can do this running:

lastSuccesfulBuildId=$(cat ../../jobs/$JOB_NAME/builds/permalinks | grep lastSuccessfulBuild | sed 's/lastSuccessfulBuild //')

Solution 4

If you want the DisplayName of the last successful job and not build number:

curl --user <username>:<tokenOrPassword> https://<url>/job/<job-name>/lastSuccessfulBuild/api/json | jq -r '.displayName'

Or in groovy

def buildName = Jenkins.instance.getItem('jobName').lastSuccessfulBuild.displayName

Solution 5

To get the last successful build number using curl:

curl --user userName:password https://url/job/jobName/api/xml?xpath=/*/lastStableBuild/number

Share:
38,760
Jason
Author by

Jason

Updated on July 09, 2022

Comments