Wait until a Jenkins build is complete

If you need to know if the job is finished, the buildNumber and buildTimestamp are not enough.

This is the gist of how I find out if a job is complete, I have it in ruby but not python so perhaps someone could update this into real code.

lastBuild = get jenkins/job/myJob/lastBuild/buildNumber
get jenkins/job/myJob/lastBuild/build?token=gogogo

currentBuild = get jenkins/job/myJob/lastBuild/buildNumber
while currentBuild  == lastBuild 
  sleep 1 

thisBuild = get jenkins/job/myJob/lastBuild/buildNumber
buildInfo = get jenkins/job/myJob/[thisBuild]/api/xml?depth=0

while buildInfo["freeStyleBuild/building"] == true
  buildInfo = get jenkins/job/myJob/[thisBuild]/api/xml?depth=0
  sleep 1

ie. I found I needed to A) wait until the build starts (new build number) and B) wait until the building finishes (building is false).


You can query the last build timestamp to determine if the build finished. Compare it to what it was just before you triggered the build, and see when it changes. To get the timestamp, add /lastBuild/buildTimestamp to your job URL

As a matter of fact, in your Jenkins, add /lastBuild/api/ to any Job, and you will see a lot of API information. It even has Python API, but I not familiar with that so can't help you further

However, if you were using XML, you can add lastBuild/api/xml?depth=0 and inside the XML, you can see the <changeSet> object with list of revisions/commit messages that triggered the build


This snippet starts build job and wait until job is done.

It is easy to start the job but we need some kind of logic to know when job is done. First we need to wait for job ID to be applied and than we can query job for details:

from jenkinsapi import jenkins

server = jenkins.Jenkins(jenkinsurl, username=username, password='******')
job = server.get_job(j_name)
prev_id = job.get_last_buildnumber()
server.build_job(j_name)
while True:
    print('Waiting for build to start...')
    if prev_id != job.get_last_buildnumber():
        break
    time.sleep(3)
print('Running...')
last_build = job.get_last_build()
while last_build.is_running():
    time.sleep(1)
print(str(last_build.get_status()))