Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get build number for jenkins job via python code

Tags:

python

jenkins

I am developing a python code to deal with jenkins using the jenkinsapi package. I am looking for a simple way to pass the job name and get the latest build number for that job. Example

from jenkinsapi import jenkins
ci_jenkins_url = "job url"
username = None
token = None
job = "Test 3"
j = jenkins.Jenkins(ci_jenkins_url, username=username, password=token)

if __name__ == "__main__":
    j.build_job(job)

This is triggering builds successfully, but I need to get the build number for proceeding further. Any help would be highly appreciated

like image 486
Trishal Avatar asked Mar 13 '23 12:03

Trishal


2 Answers

There are 2 ways :

Way 1: Using following APIs -

  • Access the same data as Python for Python clients :

    http://(jenkins_url):8080/job/(jobname)/api/python?pretty=true

  • Access the same data as JSON for JavaScript-based access :

    http://(jenkins_url):8080/job/(jobname)/api/json?pretty=true

  • Access data exposed in HTML as XML for machine consumption :

    http://(jenkins_url):8080/job/(jobname)/api/xml

From above URls, you can get latest build number from builds block. For more details : check http://(jenkins_url):8080/job/(jobname)/api/

Way2 : Using jenkinsapi module

import jenkinsapi
from jenkinsapi.jenkins import Jenkins
server = Jenkins(jenkins_url,username=<<>>,password=<<>>)
print(server.get_job("jobname").get_last_buildnumber())
like image 136
Harsha Biyani Avatar answered Mar 23 '23 16:03

Harsha Biyani


The Job object implements several methods for getting the build number of the last build, last completed build, last stable build, etc.

jenkins_server = jenkins.Jenkins(ci_jenkins_url, username=username, password=token)
my_job = jenkins_server.get_job('My Job Name')
last_build = my_job.get_last_buildnumber()

You can use Python interactively to explore the API for packages that don't have complete online documentation:

>>> jenkins_server = jenkins.Jenkins(...)
>>> job = jenkins_server.get_job('My Job Name')
>>> help(job)
like image 24
Dave Bacher Avatar answered Mar 23 '23 15:03

Dave Bacher