qdyxmas's Room

Done is better than perfect...

jenkins API for python

Using Python-Jenkins

The python-jenkins library allows management of a Jenkins server through the Jenkins REST endpoints. Below are examples to get you started using the library. If you need further help take a look at the API reference docs for more details.

Example 1: Get version of Jenkins

This is an example showing how to connect to a Jenkins instance and retrieve the Jenkins server version.

import jenkins

server = jenkins.Jenkins('http://localhost:8080', username='myuser', password='mypassword')
user = server.get_whoami()
version = server.get_version()
print('Hello %s from Jenkins %s' % (user['fullName'], version))

The above code prints the fullName attribute of the user and the version of the Jenkins master running on ‘localhost:8080’. For example, it may print “Hello John from Jenkins 2.0”.

From Jenkins version 1.426 onward you can specify an API token instead of your real password while authenticating the user against the Jenkins instance. Refer to the Jenkins Authentication wiki for details about how you can generate an API token. Once you have an API token you can pass the API token instead of a real password while creating a Jenkins instance.

Example 2: Logging into Jenkins using kerberos

Kerberos support is only enabled if you have “kerberos” python package installed. You can install the “kerberos” package from PyPI using the obvious pip command.

pip install kerberos

This might require python header files as well as kerberos header files.

If you have “kerberos” python package installed, python-jenkins tries to authenticate using kerberos automatically when the Jenkins server replies “401 Unauthorized” and indicates it supports kerberos. That is, kerberos authentication should work automagically. For a quick test, just try the following.

import jenkins

server = jenkins.Jenkins('http://localhost:8080')
print server.jobs_count()

Jenkins as such does not support kerberos, it needs to be supported by the Servlet container or a reverse proxy sitting in front of Jenkins.

Example 3: Working with Jenkins Jobs

This is an example showing how to create, configure and delete Jenkins jobs.

server.create_job('empty', jenkins.EMPTY_CONFIG_XML)
jobs = server.get_jobs()
print jobs
my_job = server.get_job_config('cool-job')
print(my_job) # prints XML configuration
server.copy_job('empty', 'empty_copy')
server.reconfig_job('empty_copy', jenkins.RECONFIG_XML)


# build a parameterized job
# requires creating and configuring the api-test job to accept 'param1' & 'param2'
server.build_job('api-test', {'param1': 'test value 1', 'param2': 'test value 2'})
last_build_number = server.get_job_info('api-test')['lastCompletedBuild']['number']
build_info = server.get_build_info('api-test', last_build_number)
print build_info

# get all jobs from the specific view
jobs = server.get_jobs(view_name='View Name')
print jobs
Example 4: Working with Jenkins Views
This is an example showing how to create, configure and delete Jenkins views.

server.create_view('EMPTY', jenkins.EMPTY_VIEW_CONFIG_XML)
view_config = server.get_view_config('EMPTY')
views = server.get_views()
print views

Example 5: Working with Jenkins Plugins

This is an example showing how to retrieve Jenkins plugins information.

plugins = server.get_plugins_info()
print plugins

The above example will print a dictionary containing all the plugins that are installed on the Jenkins server. An example of what you can expect from the get_plugins_info() method is documented in the API reference doc.

Example 6: Working with Jenkins Nodes

This is an example showing how to add, configure, enable and delete Jenkins nodes.

nodes = get_nodes()
print nodes
node_config = server.get_node_info('slave1')
print node_config

# create node with parameters
params = {
    'port': '22',
    'username': 'juser',
    'credentialsId': '10f3a3c8-be35-327e-b60b-a3e5edb0e45f',
    'host': 'my.jenkins.slave1'
    nodeDescription='my test slave',

Example 7: Working with Jenkins Build Queue

This is an example showing how to retrieve information on the Jenkins queue.

queue_info = server.get_queue_info()
id = queue_info[0].get('id')

Example 8: Working with Jenkins Cloudbees Folders

Requires the Cloudbees Folders Plugin for Jenkins.

This is an example showing how to create, configure and delete Jenkins folders.

server.create_job('folder', jenkins.EMPTY_FOLDER_XML)
server.create_job('folder/empty', jenkins.EMPTY_FOLDER_XML)
server.copy_job('folder/empty', 'folder/empty_copy')

Example 9: Updating Next Build Number

Requires the Next Build Number Plugin for Jenkins.

This is an example showing how to update the next build number for a Jenkins job.

next_bn = server.get_job_info('job_name')['nextBuildNumber']
server.set_next_build_number('job_name', next_bn + 50)

Example 10: Working with Build Promotions

Requires the Promoted Builds Plugin for Jenkins.

This is an example showing how to create, configure and delete a promotion process for an existing job.

The job in this example is named prom_job and it needs to have this config xml snippet before creating the promotion:


where prom_name is the name of the promotion that will get added to the job.

server.create_promotion('prom_name', 'prom_job', jenkins.EMPTY_PROMO_CONFIG_XML)
server.promotion_exists('prom_name', 'prom_job')
print server.get_promotions('prom_job')

server.reconfig_promotion('prom_name', 'prom_job', jenkins.PROMO_RECONFIG_XML)
print server.get_promotion_config('prom_name', 'prom_job')

server.delete_promotion('prom_name', 'prom_job')

Example 11: Waiting for Jenkins to be ready

It is possible to ask the API to wait for Jenkins to be ready with a given timeout. This can be used to aid launching of Jenkins and then waiting for the REST API to be responsive before continuing with subsequent configuration.

# timeout here is the socket connection timeout, for each connection
# attempt it will wait at most 5 seconds before assuming there is
# nothing listening. Useful where firewalls may black hole connections.
server = jenkins.Jenkins('http://localhost:8080', timeout=5)

# wait for at least 30 seconds for Jenkins to be ready
if server.wait_for_normal_op(30):
    # actions once running
    print("Jenkins failed to be ready in sufficient time")
    exit 2

Note that the timeout arg to jenkins.Jenkins() is the socket connection timeout. If you set this to be more than the timeout value passed to wait_for_normal_op(), then in cases where the underlying connection is not rejected (firewall black-hole, or slow connection) then wait_for_normal_op() may wait at least the connection timeout, or a multiple of it where multiple connection attempts are made. A connection timeout of 5 seconds and a wait timeout of 8 will result in potentially waiting 10 seconds if both connections attempts do not get responses.


125 评论

  1. Emelia

    viagra without a prescription https://viagarabig.com - viagra online viagra prescription cost of viagra per pill order viagra tablets generic viagra

  2. Gregory

    Thanks for sharing your thoughts oon Artvigil bestellen. Regards сialis ohne rezept kaufen weblage Armodafinil online kaufen

  3. Garrett

    La prsente valuation pralable finale a t prpare par le personnel des Programmes des substances existantes de Sant et d'Environnement Comme il a t mentionn prcdemment, le Rapport sur l des connaissances scientifiques sous jacentes une valuation. animal dildo dildos vibrators

  4. Juanita

    $10 general admission, $6.75 seniors. vibrators dildo animal dildo

  5. Nathan

    "The timing has to be right for something like that. You can't force anything. It's definitely something I haven't forgotten," says the busy actor. There have been a number of notable social media crime cases, topped by Derick Medina of South Miami. dog dildo vibrators wholesale dildos

  6. Rufus

    In December 1984 the agency purchased Bloom Gelb, an eight year old direct mail agency billing $15 million, which JC had been working with in connection with some of its own clients. It would not be a successful merger. cheap sex toys wholesale vibrators wholesale vibrator

  7. Jamel

    Carlos Bustillos DE 6 2, 235, Enid. Bustillos had 99 tackles (66 solo) with eight sacks as a senior for the Plainsmen. He was born in Hawaii and has also lettered in wrestling. wholesale vibrator wholesale sex toys wholesale sex toys

  8. Elsie

    We try to push each other. It a real close group so we stay on each other back about the intensity and we just try to stay aggressive on teams so we get out to a fast start. Realistic Dildo sex toys g spot vibrator

  9. Miranda

    Jordan Hillyard poses with Sparky from the Springdale Volunteer Fire Department, part of the group that greeted him home after he left the Janeway Children's Hospital this week. fake yeezy cheap air jordans cheap jordans from china

  10. Sam

    If I got into some trouble on a hole or two maybe I'm even, so I thought that was all right. Then eight and nine kind of hurt me there. Instead of playing those one under par, I play them one over par, where I really didn't miss a shot.. wholesale jerseys from china wholesale nfl jerseys from china Cheap Jerseys china

  11. Chana

    Milton, Amanda B. Miner, Subash Mishra, Daryl L. Moore, Kendal J. A New York Times 1993 review, critic Walter Goodman wrote that no guest could ask for a attentive, less threatening interrogator than Rose.Related ArticlesDecember 16, 2017Mr. Cheap Jerseys free shipping wholesale jerseys from china Cheap Jerseys china

  12. Tasha

    Jordan Graham has heart set on Aston Villa reunionJordan Graham is hoping for a reunion with former club Aston Villa. dildo penis pump wholesale vibrators

  13. yotulsgyir

    2yfVTX <a href="http://wvydssnvbuhs.com/">wvydssnvbuhs</a>, [url=http://mjprjgisghjt.com/]mjprjgisghjt[/url], [link=http://obwbtcrnxqdd.com/]obwbtcrnxqdd[/link], http://wtdlaxibqwmb.com/

  14. Flossie

    The two women took a picture which Jordan quickly put on Facebook. Really nothing special about us. I didn expect this to go that viral. cheap yeezys cheap jordans from china cheap air jordans

  15. Hassan

    A top pick, said Bonzani: the fried pickles, thin circular slices fried to perfection with a house breading. sex shop horse dildo sex shop

  16. Terry

    Awesome blog! Do you have anyy recommendations for aspiring writers? I'm planning to startt my own website soon but I'm a litrtle lost on everything. Would you advise starting with a frtee platform like Wordpress or go ffor a paid option? There are sso many choices out there that I'm totally confused .. Any suggestions? Kudos! Leihmutter deutschland homepage leihmutterschaft

  17. Janell

    Wonderful goods from you, man. I have understand your stuff previous to and you are just too fantastic. I really like what you have acquired here, really like what you're szying and the way in which you say it. You makme it entertaining and you still carde for to keep it sensible. I cann not wait too read much more from you. This is really a terrific site. Farbige Wachskerzen kaufen website Gummi Zedernöl

  18. ecoDah

    <b><a href=https://eco-corporation.ru>Септик для дачи тольятти</a></b> Автономная канализация - наиболее востребованная часть технических коммуникаций Для вас мы предлагаем высококлассные сервис по монтажу автономной канализации под ключ, владеем исключительной методикой и частным подходом к работе. Автономная канализация цена под ключ-это сегодня наш профиль Обеспечиваем лучший завершающий результат Автономная канализация в частном помещении - лучший выбор от компанииСборка септика - изрядно непростой процесс, предполагающий не только лишь строительство, но и дополнительно выбор нужной системы.

  19. Renaldo

    how to order viagra from canada https://viagaramu.com - generic viagra soft viagra generic online women viagra pills buy cheap viagra viagra how it works

  20. 온라인카지노

    Hello I am so excited I found your weblog, I really found you by accident, while I was browsing on Askjeeve for something else, Anyhow I am here now and would just like to say kudos for a tremendous post and a all round thrilling blog (I also love the theme/design), I don't have time to look over it all at the moment but I have book-marked it and also included your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the excellent work. https://www.casino369.net

  21. SVSbeirm

    Большинство из скважин со временем проведения восстановительного комплекса мероприятий могут быть снова введены в эксплуатацию. Тем более что оплата этих выполненных работ в десятки раз ниже суммы самих сооружений. Обеспечено повышение сбыта водозаборной скважины не менее 30 процентов от существующего на момент запуска задач. В восьмидесятиS% случаях скважины возобновляются до первичных данных при включении в эксплуатацию скважины, что будет альтернативой бурения новой скважины. Сотрудники нашей этой компании по Очистке Чаш Градилен и Ремонту водозаборных скважин предлагаем свои услуги всем, как частным так и общественным системам. Спецводсервис - <a href=https://svs-samara.ru/skvazhiny/uvelichenie-proizvoditelnosti-debita-vodozabornyh-skvazhin/>Увеличение производительности водозаборных скважин</a>

  22. Chang

    Hi there, I found your website by means of Google even as looking for a similar matter, your sitee came up, it appears to bbe like great. I've bookmarked itt in my google bookmarks. Hellko there, simply turned into aware of your weblog thru Google, aand lcated that it's truly informative. I am going to watcfh oout for brussels. I'll appreciaye iff you proceed this in future. Lots of people will likely be benefited from your writing. Cheers! деньги под залог авто киев website деньги под залог недвижимости киев

  23. Denny

    Good day I am so excited I found your web site, I really found you by mistake, while Iwas looking on Bing for something else, Anyhow I am herre nnow and would juxt like to say thank you for a marvelous post and a alll round entertaining blog (Ialso love thhe theme/design), I don't have time to read through it all at the minute but I have bookmarked it and also added you RSS feeds, so when I have time I will be back to read much more, Please do keep up the excellent work. взять кредит в харькове wweb pag кредит под залог дома харьков

  24. goldenslot

    บทความ : ขั้นตอน วิธีการเล่น บาคาร่าออนไลน์มือถือ https://www.golddenslot.com/

  25. Keira

    Ahaa, itts nice dialogue on the topic of this paragraph at this place at this web site, I have read all that, so now mee also commenting here. тестування релейного захисту web page юнити

  26. Alina

    where to buy cialis online with paypal https://recialisdo.com - generic cialis tadalafil tadalafil i sildenafil does medicare pay for cialis for bph cialis generic name cialis professional reviews

  27. Sandy

    buying viagra online https://viagaramu.com - generic viagra buy online buying viagra online best male enhancement pill buy viagra las vegas viagra tablets for sale

  28. Trey

    viagra coupon https://genviagaraget.com - viagra without a prescription buy generic viagra cheap viagra best price viagra buy viagra now

  29. Grace

    can i buy cialis over the counter in thailand https://gocialisget.com - cialis 5mg ou acheter du cialis sans ordonnance en france que son las pildoras cialis cialis coupons cialis 20 mg costi

  30. Mazie

    online pharmacy viagra https://viagarado.com - generic viagra price viagra tablets for men buy viagra now pills for erection viagra tablets for sale