Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve build_id of latest successful build in Jenkins?

Generally, to get the artifact of the latest successful build, I do a wget on the below URL:

http://jenkins.com/job/job_name/lastSuccessfulBuild/artifact/artifact1/jenkins.txt

Is there a way, I can do a wget on lastSuccessfulBuild and get a build_id like below?

build_id=`wget http://jenkins.p2pcredit.local/job/job_name/lastSuccessfulBuild`
like image 489
Jason Avatar asked Jul 20 '15 03:07

Jason


People also ask

How do I get the latest build number from another job in Jenkins pipeline?

Consider using getItemByFullName() instead of getItem() . This can be important if you have folders and the jobName is in another folder.

How do you know if a Jenkins Building is successful?

Check to see if a build is running or not If a build is in progress, a grep for result\":null will return 0. If a build is finished, a grep for result\":null will return 1.


2 Answers

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
like image 127
Vitalii Elenhaupt Avatar answered Oct 02 '22 16:10

Vitalii Elenhaupt


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

like image 27
networm Avatar answered Oct 02 '22 16:10

networm