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.

标签 

205 评论

  1. corporate logo golf balls
    /回复

    If some one needs to be updated with hottest technologies therefore he must be visit this web page and be up to date everyday. http://babajons.com/product/chickpea-3/

  2. http://media.saychik.com/
    /回复

    whoah this blog is excellent i really like studying your posts. Keep up the great work! You understand, many people are searching around for this info, you could aid them greatly. http://media.saychik.com/index.php?qa=user&qa_1=gallagherhove22

  3. wordpress theme screenshot
    /回复

    You really make it appear so easy together with your presentation however I find this matter to be really something which I feel I would by no means understand. It kind of feels too complicated and extremely vast for me. I am taking a look forward on your next post, I'll try to get the grasp of it! https://www.openlearning.com/u/seomasterpress-qi8ivc/

  4. 우리카지노
    /回复

    Hello it's me, I am also visiting this web site daily, this web page is truly fastidious and the visitors are really sharing good thoughts. https://sites.google.com/view/online-gambling-keep-control/home

  5. قصة عشق مسلسل انت اطرق بابي 12
    /回复

    I'm impressed, I have to admit. Seldom do I come across a blog that's both educative and engaging, and let me tell you, you have hit the nail on the head. The issue is something not enough men and women are speaking intelligently about. I'm very happy that I stumbled across this in my search for something regarding this. https://penzu.com/p/7615c012

  6. 变性人与男人
    /回复

    全部大学生入团申请书部队入团申请书军人入团申请书共青团入团申请书范文共青团成立共青团团旗优秀团员团员退团年龄团员证更多 https://superiorrussia.ru/

  7. orbita watch winders
    /回复

    Today, I went to the beach with my children. I found a sea shell and gave it to my 4 year old daughter and said "You can hear the ocean if you put this to your ear." She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone! http://sdbrasil.com.br/new-partnership-bubenzorweg-for-bugatti/

  8. قصة عشق baraj
    /回复

    I quite like reading through an article that will make people think. Also, thanks for permitting me to comment! https://www.wishlistr.com/steven6358

  9. pet stain removal minneapolis
    /回复

    I feel that is among the so much vital information for me. And i am glad reading your article. However want to commentary on few general things, The website style is great, the articles is actually great : D. Good process, cheers http://yuzuki.s6.xrea.com/cgi-bin/cat/apeboard_plus.cgi/%20targe

  10. قصة عشق قيامة ارطغرل الموسم الثالث الحلقة
    /回复

    Nice blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple adjustements would really make my blog stand out. Please let me know where you got your theme. Kudos https://seoexperttipsbysohel.wordpress.com/2020/10/21/love-story/

  11. 肌肉男
    /回复

    全部大学生入团申请书部队入团申请书军人入团申请书共青团入团申请书范文共青团成立共青团团旗优秀团员团员退团年龄团员证更多 https://superiorrussia.ru/

  12. eden prairie carpet cleaning
    /回复

    Hi there I am so delighted I found your blog page, I really found you by error, while I was researching on Aol for something else, Anyways I am here now and would just like to say thank you for a tremendous post and a all round enjoyable blog (I also love the theme/design), I don't have time to go through it all at the moment but I have bookmarked it and also added in your RSS feeds, so when I have time I will be back to read more, Please do keep up the superb job. http://www.emileo.com/our-github-responsitory/

  13. 英国
    /回复

    全部大学生入团申请书部队入团申请书军人入团申请书共青团入团申请书范文共青团成立共青团团旗优秀团员团员退团年龄团员证更多 https://superiorrussia.ru/

  14. Buben Zorweg watch winder safe
    /回复

    Awesome! Its genuinely awesome article, I have got much clear idea on the topic of from this post. http://cu-jembatankasih.org/gallery/dsc_0229/

  15. titleist logo golf balls
    /回复

    I know this site gives quality based articles or reviews and additional information, is there any other website which provides these stuff in quality? http://www.linsladetaekwondo.co.uk/uncategorized/hello-world/

  16. Joycelyn
    /回复

    Normally I do not learn post on blogs, but I wish to say that this write-up very compelled me to take a look at and do so! Your writing taste has been amazed me. Thank you, quite nice article. https://sites.google.com/view/online-poker-for-beginners-/home

  17. titleist logo golf balls
    /回复

    After I originally left a comment I appear to have clicked on the -Notify me when new comments are added- checkbox and from now on each time a comment is added I receive 4 emails with the same comment. Perhaps there is a means you can remove me from that service? Thanks! http://lshdigital.co.kr/LSH06p1/931501

  18. Iva
    /回复

    Stunning quest there. What occurred after? Take care! изделия из искусственного камня web site декоративный кирпич

  19. seo services what is
    /回复

    Hi there colleagues, how is all, and what you want to say about this paragraph, in my view its really amazing in support of me. https://setiathome.berkeley.edu/show_user.php?userid=10971457

  20. Rosemount mortgage loan
    /回复

    Hey just wanted to give you a quick heads up. The words in your article seem to be running off the screen in Safari. I'm not sure if this is a format issue or something to do with web browser compatibility but I figured I'd post to let you know. The design and style look great though! Hope you get the problem resolved soon. Many thanks http://www.minnesotamortgageguy.com/conventional-mortgages

  21. 온라인카지노
    /回复

    I am sure this article has touched all the internet people, its really really pleasant post on building up new blog. https://sites.google.com/view/bingo-maths/home

  22. custom boat canvas cover
    /回复

    Hello There. I found your blog the usage of msn. That is a really well written article. I will be sure to bookmark it and return to learn extra of your helpful info. Thanks for the post. I'll certainly comeback. https://allstarupholsterymn.com/canvas-enclosure/

  23. Latanya
    /回复

    Heya this is kind of of off topic but I was wanting to know if blogs use WYSIWYG editors or iif you have too majually coxe with HTML. I'm starting a blog soon but have no coding knowledge so I wanted to get guidance from someone with experience. Any help would bbe greatly appreciated! утепление пенопластовой крошкой site утепление пенопластом снаружи

  24. 온라인카지노
    /回复

    Attractive section of content. I just stumbled upon your blog and in accession capital to assert that I get in fact enjoyed account your blog posts. Any way I will be subscribing to your feeds and even I achievement you access consistently quickly. https://sites.google.com/view/set-up-free-private-online/home

  25. street rod upholstery
    /回复

    I got this web page from my pal who informed me about this web site and at the moment this time I am visiting this website and reading very informative articles at this place. https://allstarupholsterymn.com/upholstery/street-rod/

  26. Levi
    /回复

    Hello, Neat post. There's an issue with your site in web explorer, miight test this? IE still is the marketplace leader and a big component to folks will miss your magnificent writing becxause of this problem. анаболические стероиды website халотест

  27. hot rod convertible tops
    /回复

    Fantastic goods from you, man. I've understand your stuff previous to and you are just extremely wonderful. I really like what you have acquired here, certainly like what you are stating and the way in which you say it. You make it enjoyable and you still care for to keep it sensible. I can't wait to read far more from you. This is really a great web site. http://www.raizcimentaciones.es/blog-raiz-cimentaciones/item/5-grietas-en-las-viviendaserror=DIFFERENT_DOMAIN?

  28. minneapolis professional carpet cleaning
    /回复

    A motivating discussion is definitely worth comment. I do believe that you should publish more on this topic, it may not be a taboo subject but usually people don't talk about such topics. To the next! Cheers!! http://cpaac.fr/roux-67-montagne-carte-postale-cantal/

  29. Lane
    /回复

    Nice blog here! Also yoour website loads up fast! What host are you using? Can I get your affiliate link to your host? I wish my site loaded up as quickpy as yours lol район слободка бердянск web site жильё бердянская коса

  30. محترف سيو
    /回复

    Greetings! Very helpful advice within this article! It is the little changes that produce the largest changes. Many thanks for sharing! https://able2know.org/user/barron8965/

评论