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.build_job('empty')
server.disable_job('empty')
server.copy_job('empty', 'empty_copy')
server.enable_job('empty_copy')
server.reconfig_job('empty_copy', jenkins.RECONFIG_XML)

server.delete_job('empty')
server.delete_job('empty_copy')

# 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()
server.delete_view('EMPTY')
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.

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

# create node with parameters
params = {
    'port': '22',
    'username': 'juser',
    'credentialsId': '10f3a3c8-be35-327e-b60b-a3e5edb0e45f',
    'host': 'my.jenkins.slave1'
}
server.create_node(
    'slave1',
    nodeDescription='my test slave',
    remoteFS='/home/juser',
    labels='precise',
    exclusive=True,
    launcher=jenkins.LAUNCHER_SSH,
    launcher_params=params)

Example 7: Working with Jenkins Build Queue

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

server.build_job('foo')
queue_info = server.get_queue_info()
id = queue_info[0].get('id')
server.cancel_queue(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')
server.delete_job('folder/empty_copy')
server.delete_job('folder')

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:

<properties>
   <hudson.plugins.promoted__builds.JobPropertyImpl>
   <activeProcessNames>
      <string>prom_name</string>
    </activeProcessNames>
  </hudson.plugins.promoted__builds.JobPropertyImpl>
</properties>

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
    ...
else:
    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.

标签 

153 评论

  1. Emely
    /回复

    Hello! I just wanted to ask iif you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing months of hard work duee to no back up. Do you have any solutions to prevent hackers? Super kamagra kaufen deutschland webpage viagra gennerika 100mg

  2. Darla
    /回复

    gookerdoughboy777 https://gookerdoughboy777.blogspot.com/2020/12 Excellent items from you, man. I've be mindful your stuff previous to and you're just too magnificent. I actually like what you've received here, certainly like what you are saying and the best way wherein you say it. You make it entertaining and you still take care of to stay it wise. I can't wait to learn far more from you. This is actually a great web site.

  3. Horace
    /回复

    pay to write paper https://researchpapero.com - paper writers for college good research topic research paper titles write a research paper writing term papers

  4. Meagan
    /回复

    Fan-effing-tastic blogger! - goto penis stretcher weight - It's built in Australia. Message Meagan Razo for pics!

  5. Augustina
    /回复

    scholarship example essays https://getessaypro.com - buy an essays topics for expository essays type my essay argumentative essay topics essay on topic

  6. Clark
    /回复

    What's up i am kavin, its my first occasion to commenting anyplace, when i read this paragraph i thought i could also create comment due to this good post. Cialis generika preisvergleich homepage potenzmittel online

  7. France
    /回复

    Greate article. Keep posting such kind of info on your blog. Im really impressed by your site. Hey there, You've performed a fantastic job. I'll definitely digg it and in my opinion recommend to my friends. I am confident they will be benefited from this web site.click here manifestation magic review

  8. Judith
    /回复

    mail order viagra https://goviagarato.com - online generic viagra ed pills online subscription viagra without doctor prescription female viagra pfizer viagra price

  9. Leola
    /回复

    What's up i am kavin, itts my first time to commenting anywhere, when i read this posat i thought i could also make comment due to this sensible article. Trading strategies website trading strategy

  10. MonzaBetly
    /回复

    бог даст только для вас большой депозит https://teplocel.ru/includes/pgs/igrovue_avtomatu_s_fruktami.html https://arnest.ru/wp-includes/list/?kakie_bonusu_mozghno_poluchit_v_igrovuh_avtomatah_kazino_vulkan.html https://gazcom74.ru/docs/pages/?legkiy_sposob_poluchit_bolshoy_vuigrush_v_kazino_vulkan.html http://azbukadiet.ru/news/kak_proyti_verifikaciu_na_sayte_kazino_vulkan.html http://tounb.ru/opac/elm/?kazino_vulkan_besplatno_i_bez_registracii.html

  11. Emery
    /回复

    prescription tadalafil online

  12. Toni
    /回复

    cash advance loans payday loans cash advance payday loan advances get loans online payday loan cash advance

  13. MeezaTilk
    /回复

    и кроме того только вам опытный гемблер http://www.granitonline.ch/?option=com_k2&view=itemlist&task=user&id=46045 http://www.meanfrutta.it/?option=com_k2&view=itemlist&task=user&id=360073 http://krasnogorsk-makler.ru/realty/demand/76806 http://old.ho4uletat.ru/coaches/irina-norna/otzivy/13801 http://www.ubiqueict.com/?option=com_k2&view=itemlist&task=user&id=2084410 TL4kRi3x

  14. Cecila
    /回复

    payday loan advances same day loans cash loan small loans payday cash advance loans online

  15. دعم سناب شات
    /回复

    Hi there! I know this is kinda off topic but I was wondering which blog platform are you using for this site? I'm getting fed up of Wordpress because I've had problems with hackers and I'm looking at alternatives for another platform. I would be awesome if you could point me in the direction of a good platform. http://www.costaricadreamhomes.com/UserProfile/tabid/399/UserId/1579073/Default.aspx

  16. snapchat features
    /回复

    Excellent, what a website it is! This webpage gives valuable facts to us, keep it up. https://www.theverge.com/users/ROBERTd87

  17. Margarito
    /回复

    It is not my first ttime to pay a quick visit this site, i am browsing this site dailly and get nice information from here all the time. หลอกลวงตลาดความมั่งคั่งออนไลน์ website แอพตัวเลือกไบนารี

  18. الطيب
    /回复

    Hello to all, how is all, I think every one is getting more from this web site, and your views are good designed for new people. https://weheartit.com/siffft

  19. Ramon
    /回复

    คลิปหลุด

  20. samsung girl
    /回复

    I get pleasure from, cause I found exactly what I used to be having a look for. You've ended my 4 day long hunt! God Bless you man. Have a nice day. Bye https://diigo.com/0kujtr

  21. samsung girl
    /回复

    This design is steller! You most certainly know how to keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (well, almost...HaHa!) Fantastic job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool! https://pixelation.org/index.php?action=profile;area=summary;u=275789

  22. Samsung Galaxy S III
    /回复

    Hello, I would like to subscribe for this blog to obtain latest updates, thus where can i do it please assist. http://onlineboxing.net/jforum/user/profile/107124.page

  23. samsung flip phone
    /回复

    Simply wish to say your article is as astonishing. The clarity in your post is just cool and i can assume you are an expert on this subject. Well with your permission allow me to grab your feed to keep up to date with forthcoming post. Thanks a million and please carry on the rewarding work. https://www.quora.com/profile/Brandon-Marsh-73

  24. pubg mobile free gifts
    /回复

    Just want to say your article is as surprising. The clearness in your post is simply great and i can assume you are an expert on this subject. Fine with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please carry on the gratifying work. https://www.openstreetmap.org/user/Hove%20Massey

  25. Mothjam
    /回复

    <a href=https://hqd.wiki/>hqd светится зеленым</a> электронная сигарета ролики

  26. متجر عطور
    /回复

    I don't even know how I ended up here, but I thought this post was great. I don't know who you are but certainly you're going to a famous blogger if you aren't already ;) Cheers! https://peopletalentlink.com/blog/view/564320/just-how-much-does-a-diamond-necklace-price

  27. عقد الماس
    /回复

    Pretty component to content. I just stumbled upon your website and in accession capital to claim that I acquire in fact enjoyed account your blog posts. Anyway I'll be subscribing in your augment and even I fulfillment you get admission to constantly fast. https://pbase.com/topics/textdigger6/how_much_does_a_diamond_set

  28. Yasmin
    /回复

    can erectile dysfunction be hereditary pharmaceptica.com

  29. سلسلة الماس
    /回复

    Hello, Neat post. There is a problem together with your web site in internet explorer, may check this? IE nonetheless is the marketplace leader and a good section of people will miss your excellent writing because of this problem. https://www.gamespot.com/profile/scentsled05/about-me/

  30. rush card
    /回复

    Thank you a lot for sharing this with all of us you really know what you are speaking about! Bookmarked. Kindly also talk over with my website =). We will have a hyperlink alternate contract among us https://www.designjobs.com/users/shelton639

评论