1PYTHONJENKINS(1) Python Jenkins PYTHONJENKINS(1)
2
3
4
6 pythonjenkins - Python Jenkins Documentation
7
8 Python Jenkins is a python wrapper for the Jenkins REST API which aims
9 to provide a more conventionally pythonic way of controlling a Jenkins
10 server. It provides a higher-level API containing a number of conve‐
11 nience functions.
12
13 We like to use python-jenkins to automate our Jenkins servers. Here are
14 some of the things you can use it for:
15
16 • Create new jobs
17
18 • Copy existing jobs
19
20 • Delete jobs
21
22 • Update jobs
23
24 • Get a job's build information
25
26 • Get Jenkins master version information
27
28 • Get Jenkins plugin information
29
30 • Start a build on a job
31
32 • Create nodes
33
34 • Enable/Disable nodes
35
36 • Get information on nodes
37
38 • Create/delete/reconfig views
39
40 • Put server in shutdown mode (quiet down)
41
42 • List running builds
43
44 • Delete builds
45
46 • Wipeout job workspace
47
48 • Create/delete/update folders [1]
49
50 • Set the next build number [2]
51
52 • Install plugins
53
54 • and many more..
55
56 To install:
57
58 $ sudo python setup.py install
59
60 Online documentation:
61
62 • http://python-jenkins.readthedocs.org/en/latest/
63
65 Bug report:
66
67 • https://bugs.launchpad.net/python-jenkins
68
69 Repository:
70
71 • https://git.openstack.org/cgit/openstack/python-jenkins
72
73 Cloning:
74
75 • git clone https://git.openstack.org/openstack/python-jenkins
76
77 Patches are submitted via Gerrit at:
78
79 • https://review.openstack.org/
80
81 Please do not submit GitHub pull requests, they will be automatically
82 closed.
83
84 The python-jenkins developers communicate in the #openstack-jjb channel
85 on Freenode's IRC network.
86
87 More details on how you can contribute is available on our wiki at:
88
89 • http://docs.openstack.org/infra/manual/developers.html
90
92 Be sure that you lint code before created an code review. The easiest
93 way to do this is to install git pre-commit hooks.
94
96 Then install the required python packages using pip:
97
98 $ sudo pip install python-jenkins
99
101 [1] The free Cloudbees Folders Plugin provides support for a subset of
102 the full folders functionality. For the complete capabilities you
103 will need the paid for version of the plugin.
104
105 [2] The Next Build Number Plugin provides support for setting the next
106 build number.
107
109 See examples at examples
110
111 exception jenkins.JenkinsException
112 General exception type for jenkins-API-related failures.
113
114 exception jenkins.NotFoundException
115 A special exception to call out the case of receiving a 404.
116
117 exception jenkins.EmptyResponseException
118 A special exception to call out the case receiving an empty re‐
119 sponse.
120
121 exception jenkins.BadHTTPException
122 A special exception to call out the case of a broken HTTP re‐
123 sponse.
124
125 exception jenkins.TimeoutException
126 A special exception to call out in the case of a socket timeout.
127
128 class jenkins.WrappedSession
129 A wrapper for requests.Session to override ‘verify’ property,
130 ignoring REQUESTS_CA_BUNDLE environment variable.
131
132 This is a workaround for
133 https://github.com/kennethreitz/requests/issues/3829 (will be
134 fixed in requests 3.0.0)
135
136 merge_environment_settings(url, proxies, stream, verify, *args,
137 **kwargs)
138 Check the environment and merge it with some settings.
139
140 Return type
141 dict
142
143 class jenkins.Jenkins(url, username=None, password=None, timeout=<ob‐
144 ject object>)
145 Create handle to Jenkins instance.
146
147 All methods will raise JenkinsException on failure.
148
149 Parameters
150
151 • url – URL of Jenkins server, str
152
153 • username – Server username, str
154
155 • password – Server password, str
156
157 • timeout – Server connection timeout in secs (default:
158 not set), int
159
160 maybe_add_crumb(req)
161
162 get_job_info(name, depth=0, fetch_all_builds=False)
163 Get job information dictionary.
164
165 Parameters
166
167 • name – Job name, str
168
169 • depth – JSON depth, int
170
171 • fetch_all_builds – If true, all builds will be
172 retrieved from Jenkins. Otherwise, Jenkins will
173 only return the most recent 100 builds. This
174 comes at the expense of an additional API call
175 which may return significant amounts of data.
176 bool
177
178 Returns
179 dictionary of job information
180
181 get_job_info_regex(pattern, depth=0, folder_depth=0,
182 folder_depth_per_request=10)
183
184 Get a list of jobs information that contain names which
185 match the
186 regex pattern.
187
188 Parameters
189
190 • pattern – regex pattern, str
191
192 • depth – JSON depth, int
193
194 • folder_depth – folder level depth to search int
195
196 • folder_depth_per_request – Number of levels to
197 fetch at once, int. See get_all_jobs().
198
199 Returns
200 List of jobs info, list
201
202 get_job_name(name)
203 Return the name of a job using the API.
204
205 That is roughly an identity method which can be used to
206 quickly verify a job exists or is accessible without
207 causing too much stress on the server side.
208
209 Parameters
210 name – Job name, str
211
212 Returns
213 Name of job or None
214
215 debug_job_info(job_name)
216 Print out job info in more readable format.
217
218 jenkins_open(req, add_crumb=True, resolve_auth=True)
219 Return the HTTP response body from a requests.Request.
220
221 Returns
222 str
223
224 jenkins_request(req, add_crumb=True, resolve_auth=True)
225 Utility routine for opening an HTTP request to a Jenkins
226 server.
227
228 Parameters
229
230 • req – A requests.Request to submit.
231
232 • add_crumb – If True, try to add a crumb header
233 to this req before submitting. Defaults to True.
234
235 • resolve_auth – If True, maybe add authentica‐
236 tion. Defaults to True.
237
238 Returns
239 A requests.Response object.
240
241 get_queue_item(number, depth=0)
242 Get information about a queued item (to-be-created job).
243
244 The returned dict will have a “why” key if the queued
245 item is still waiting for an executor.
246
247 The returned dict will have an “executable” key if the
248 queued item is running on an executor, or has completed
249 running. Use this to determine the job number / URL.
250
251 Parameters
252 name – queue number, int
253
254 Returns
255 dictionary of queued information, dict
256
257 get_build_info(name, number, depth=0)
258 Get build information dictionary.
259
260 Parameters
261
262 • name – Job name, str
263
264 • number – Build number, int
265
266 • depth – JSON depth, int
267
268 Returns
269 dictionary of build information, dict
270
271 Example:
272
273 >>> next_build_number = server.get_job_info('build_name')['nextBuildNumber']
274 >>> output = server.build_job('build_name')
275 >>> from time import sleep; sleep(10)
276 >>> build_info = server.get_build_info('build_name', next_build_number)
277 >>> print(build_info)
278 {u'building': False, u'changeSet': {u'items': [{u'date': u'2011-12-19T18:01:52.540557Z', u'msg': u'test', u'revision': 66, u'user': u'unknown', u'paths': [{u'editType': u'edit', u'file': u'/branches/demo/index.html'}]}], u'kind': u'svn', u'revisions': [{u'module': u'http://eaas-svn01.i3.level3.com/eaas', u'revision': 66}]}, u'builtOn': u'', u'description': None, u'artifacts': [{u'relativePath': u'dist/eaas-87-2011-12-19_18-01-57.war', u'displayPath': u'eaas-87-2011-12-19_18-01-57.war', u'fileName': u'eaas-87-2011-12-19_18-01-57.war'}, {u'relativePath': u'dist/eaas-87-2011-12-19_18-01-57.war.zip', u'displayPath': u'eaas-87-2011-12-19_18-01-57.war.zip', u'fileName': u'eaas-87-2011-12-19_18-01-57.war.zip'}], u'timestamp': 1324317717000, u'number': 87, u'actions': [{u'parameters': [{u'name': u'SERVICE_NAME', u'value': u'eaas'}, {u'name': u'PROJECT_NAME', u'value': u'demo'}]}, {u'causes': [{u'userName': u'anonymous', u'shortDescription': u'Started by user anonymous'}]}, {}, {}, {}], u'id': u'2011-12-19_18-01-57', u'keepLog': False, u'url': u'http://eaas-jenkins01.i3.level3.com:9080/job/build_war/87/', u'culprits': [{u'absoluteUrl': u'http://eaas-jenkins01.i3.level3.com:9080/user/unknown', u'fullName': u'unknown'}], u'result': u'SUCCESS', u'duration': 8826, u'fullDisplayName': u'build_war #87'}
279
280 get_build_env_vars(name, number, depth=0)
281 Get build environment variables.
282
283 Parameters
284
285 • name – Job name, str
286
287 • number – Build number, int
288
289 • depth – JSON depth, int
290
291 Returns
292 dictionary of build env vars, dict or None for
293 workflow jobs, or if InjectEnvVars plugin not in‐
294 stalled
295
296 get_build_test_report(name, number, depth=0)
297 Get test results report.
298
299 Parameters
300
301 • name – Job name, str
302
303 • number – Build number, int
304
305 Returns
306 dictionary of test report results, dict or None if
307 there is no Test Report
308
309 get_queue_info()
310
311 Returns
312 list of job dictionaries, [dict]
313
314 Example::
315
316 >>> queue_info = server.get_queue_info()
317 >>> print(queue_info[0])
318 {u'task': {u'url': u'http://your_url/job/my_job/', u'color': u'aborted_anime', u'name': u'my_job'}, u'stuck': False, u'actions': [{u'causes': [{u'shortDescription': u'Started by timer'}]}], u'buildable': False, u'params': u'', u'buildableStartMilliseconds': 1315087293316, u'why': u'Build #2,532 is already in progress (ETA:10 min)', u'blocked': True}
319
320 cancel_queue(id)
321 Cancel a queued build.
322
323 Parameters
324 id – Jenkins job id number for the build, int
325
326 get_info(item='', query=None)
327 Get information on this Master or item on Master.
328
329 This information includes job list and view information
330 and can be used to retreive information on items such as
331 job folders.
332
333 Parameters
334
335 • item – item to get information about on this
336 Master
337
338 • query – xpath to extract information about on
339 this Master
340
341 Returns
342 dictionary of information about Master or item,
343 dict
344
345 Example:
346
347 >>> info = server.get_info()
348 >>> jobs = info['jobs']
349 >>> print(jobs[0])
350 {u'url': u'http://your_url_here/job/my_job/', u'color': u'blue',
351 u'name': u'my_job'}
352
353 get_whoami(depth=0)
354 Get information about the user account that authenticated
355 to Jenkins. This is a simple way to verify that your cre‐
356 dentials are correct.
357
358 Returns
359 Information about the current user dict
360
361 Example:
362
363 >>> me = server.get_whoami()
364 >>> print me['fullName']
365 >>> 'John'
366
367 get_version()
368 Get the version of this Master.
369
370 Returns
371 This master’s version number str
372
373 Example:
374
375 >>> info = server.get_version()
376 >>> print info
377 >>> 1.541
378
379 get_plugins_info(depth=2)
380 Get all installed plugins information on this Master.
381
382 This method retrieves information about each plugin that
383 is installed on master returning the raw plugin data in a
384 JSON format.
385
386 Deprecated since version 0.4.9: Use get_plugins() in‐
387 stead.
388
389
390 Parameters
391 depth – JSON depth, int
392
393 Returns
394 info on all plugins [dict]
395
396 Example:
397
398 >>> info = server.get_plugins_info()
399 >>> print(info)
400 [{u'backupVersion': None, u'version': u'0.0.4', u'deleted': False,
401 u'supportsDynamicLoad': u'MAYBE', u'hasUpdate': True,
402 u'enabled': True, u'pinned': False, u'downgradable': False,
403 u'dependencies': [], u'url':
404 u'http://wiki.jenkins-ci.org/display/JENKINS/Gearman+Plugin',
405 u'longName': u'Gearman Plugin', u'active': True, u'shortName':
406 u'gearman-plugin', u'bundled': False}, ..]
407
408 get_plugin_info(name, depth=2)
409 Get an installed plugin information on this Master.
410
411 This method retrieves information about a specific plugin
412 and returns the raw plugin data in a JSON format. The
413 passed in plugin name (short or long) must be an exact
414 match.
415
416 NOTE:
417 Calling this method will query Jenkins fresh for the
418 information for all plugins on each call. If you need
419 to retrieve information for multiple plugins it’s rec‐
420 ommended to use get_plugins() instead, which will re‐
421 turn a multi key dictionary that can be accessed via
422 either the short or long name of the plugin.
423
424 Parameters
425
426 • name – Name (short or long) of plugin, str
427
428 • depth – JSON depth, int
429
430 Returns
431 a specific plugin dict
432
433 Example:
434
435 >>> info = server.get_plugin_info("Gearman Plugin")
436 >>> print(info)
437 {u'backupVersion': None, u'version': u'0.0.4', u'deleted': False,
438 u'supportsDynamicLoad': u'MAYBE', u'hasUpdate': True,
439 u'enabled': True, u'pinned': False, u'downgradable': False,
440 u'dependencies': [], u'url':
441 u'http://wiki.jenkins-ci.org/display/JENKINS/Gearman+Plugin',
442 u'longName': u'Gearman Plugin', u'active': True, u'shortName':
443 u'gearman-plugin', u'bundled': False}
444
445 get_plugins(depth=2)
446 Return plugins info using helper class for version com‐
447 parison
448
449 This method retrieves information about all the installed
450 plugins and uses a Plugin helper class to simplify ver‐
451 sion comparison. Also uses a multi key dict to allow re‐
452 trieval via either short or long names.
453
454 When printing/dumping the data, the version will trans‐
455 parently return a unicode string, which is exactly what
456 was previously returned by the API.
457
458 Parameters
459 depth – JSON depth, int
460
461 Returns
462 info on all plugins [dict]
463
464 Example:
465
466 >>> j = Jenkins()
467 >>> info = j.get_plugins()
468 >>> print(info)
469 {('gearman-plugin', 'Gearman Plugin'):
470 {u'backupVersion': None, u'version': u'0.0.4',
471 u'deleted': False, u'supportsDynamicLoad': u'MAYBE',
472 u'hasUpdate': True, u'enabled': True, u'pinned': False,
473 u'downgradable': False, u'dependencies': [], u'url':
474 u'http://wiki.jenkins-ci.org/display/JENKINS/Gearman+Plugin',
475 u'longName': u'Gearman Plugin', u'active': True, u'shortName':
476 u'gearman-plugin', u'bundled': False}, ...}
477
478 get_jobs(folder_depth=0, folder_depth_per_request=10,
479 view_name=None)
480 Get list of jobs.
481
482 Each job is a dictionary with ‘name’, ‘url’, ‘color’ and
483 ‘fullname’ keys.
484
485 If the view_name parameter is present, the list of jobs
486 will be limited to only those configured in the specified
487 view. In this case, the job dictionary ‘fullname’ key
488 would be equal to the job name.
489
490 Parameters
491
492 • folder_depth – Number of levels to search, int.
493 By default 0, which will limit search to
494 toplevel. None disables the limit.
495
496 • folder_depth_per_request – Number of levels to
497 fetch at once, int. See get_all_jobs().
498
499 • view_name – Name of a Jenkins view for which to
500 retrieve jobs, str. By default, the job list is
501 not limited to a specific view.
502
503 Returns
504 list of jobs, [{str: str, str: str, str: str, str:
505 str}]
506
507 Example:
508
509 >>> jobs = server.get_jobs()
510 >>> print(jobs)
511 [{
512 u'name': u'all_tests',
513 u'url': u'http://your_url.here/job/all_tests/',
514 u'color': u'blue',
515 u'fullname': u'all_tests'
516 }]
517
518 get_all_jobs(folder_depth=None, folder_depth_per_request=10)
519 Get list of all jobs recursively to the given folder
520 depth.
521
522 Each job is a dictionary with ‘name’, ‘url’, ‘color’ and
523 ‘fullname’ keys.
524
525 Parameters
526
527 • folder_depth – Number of levels to search, int.
528 By default None, which will search all levels. 0
529 limits to toplevel.
530
531 • folder_depth_per_request – Number of levels to
532 fetch at once, int. By default 10, which is usu‐
533 ally enough to fetch all jobs using a single re‐
534 quest and still easily fits into an HTTP re‐
535 quest.
536
537 Returns
538 list of jobs, [ { str: str} ]
539
540 NOTE:
541 On instances with many folders it would not be effi‐
542 cient to fetch each folder separately, hence
543 folder_depth_per_request levels are fetched at once
544 using the tree query parameter:
545
546 ?tree=jobs[url,color,name,jobs[...,jobs[...,jobs[...,jobs]]]]
547
548 If there are more folder levels than the query asks
549 for, Jenkins returns empty [1] objects at the deepest
550 level:
551
552 {"name": "folder", "url": "...", "jobs": [{}, {}, ...]}
553
554 This makes it possible to detect when additional re‐
555 quests are needed.
556
557 [1] Actually recent Jenkins includes a _class field
558 everywhere, but it’s missing the requested
559 fields.
560
561 copy_job(from_name, to_name)
562 Copy a Jenkins job.
563
564 Will raise an exception whenever the source and destina‐
565 tion folder for this jobs won’t be the same.
566
567 Parameters
568
569 • from_name – Name of Jenkins job to copy from,
570 str
571
572 • to_name – Name of Jenkins job to copy to, str
573
574 Throws JenkinsException whenever the source and destina‐
575 tion folder are not the same
576
577 rename_job(from_name, to_name)
578 Rename an existing Jenkins job
579
580 Will raise an exception whenever the source and destina‐
581 tion folder for this jobs won’t be the same.
582
583 Parameters
584
585 • from_name – Name of Jenkins job to rename, str
586
587 • to_name – New Jenkins job name, str
588
589 Throws JenkinsException whenever the source and destina‐
590 tion folder are not the same
591
592 delete_job(name)
593 Delete Jenkins job permanently.
594
595 Parameters
596 name – Name of Jenkins job, str
597
598 enable_job(name)
599 Enable Jenkins job.
600
601 Parameters
602 name – Name of Jenkins job, str
603
604 disable_job(name)
605 Disable Jenkins job.
606
607 To re-enable, call Jenkins.enable_job().
608
609 Parameters
610 name – Name of Jenkins job, str
611
612 set_next_build_number(name, number)
613 Set a job’s next build number.
614
615 The current next build number is contained within the job
616 information retrieved using Jenkins.get_job_info(). If
617 the specified next build number is less than the last
618 build number, Jenkins will ignore the request.
619
620 Note that the Next Build Number Plugin must be installed
621 to enable this functionality.
622
623 Parameters
624
625 • name – Name of Jenkins job, str
626
627 • number – Next build number to set, int
628
629 Example:
630
631 >>> next_bn = server.get_job_info('job_name')['nextBuildNumber']
632 >>> server.set_next_build_number('job_name', next_bn + 50)
633
634 job_exists(name)
635 Check whether a job exists
636
637 Parameters
638 name – Name of Jenkins job, str
639
640 Returns
641 True if Jenkins job exists
642
643 jobs_count()
644 Get the number of jobs on the Jenkins server
645
646 Returns
647 Total number of jobs, int
648
649 assert_job_exists(name, exception_message='job[%s] does not ex‐
650 ist')
651 Raise an exception if a job does not exist
652
653 Parameters
654
655 • name – Name of Jenkins job, str
656
657 • exception_message – Message to use for the ex‐
658 ception. Formatted with name
659
660 Throws JenkinsException whenever the job does not exist
661
662 create_folder(folder_name, ignore_failures=False)
663 Create a new Jenkins folder
664
665 Parameters
666
667 • folder_name – Name of Jenkins Folder, str
668
669 • ignore_failures – if True, don’t raise if it was
670 not possible to create the folder, bool
671
672 upsert_job(name, config_xml)
673 Create a new Jenkins job or reconfigures it if it exists
674
675 Parameters
676
677 • name – Name of Jenkins job, str
678
679 • config_xml – config file text, str
680
681 check_jenkinsfile_syntax(jenkinsfile)
682 Checks if a Pipeline Jenkinsfile has a valid syntax
683
684 Parameters
685 jenkinsfile – Jenkinsfile text, str
686
687 Returns
688 List of errors in the Jenkinsfile. Empty list if
689 no errors.
690
691 create_job(name, config_xml)
692 Create a new Jenkins job
693
694 Parameters
695
696 • name – Name of Jenkins job, str
697
698 • config_xml – config file text, str
699
700 get_job_config(name)
701 Get configuration of existing Jenkins job.
702
703 Parameters
704 name – Name of Jenkins job, str
705
706 Returns
707 job configuration (XML format)
708
709 reconfig_job(name, config_xml)
710 Change configuration of existing Jenkins job.
711
712 To create a new job, see Jenkins.create_job().
713
714 Parameters
715
716 • name – Name of Jenkins job, str
717
718 • config_xml – New XML configuration, str
719
720 build_job_url(name, parameters=None, token=None)
721 Get URL to trigger build job.
722
723 Authenticated setups may require configuring a token on
724 the server side.
725
726 Use list of two membered tuples to supply parameters with
727 multi select options.
728
729 Parameters
730
731 • name – Name of Jenkins job, str
732
733 • parameters – parameters for job, or None., dict
734 or list of two membered tuples
735
736 • token – (optional) token for building job, str
737
738 Returns
739 URL for building job
740
741 build_job(name, parameters=None, token=None)
742 Trigger build job.
743
744 This method returns a queue item number that you can pass
745 to Jenkins.get_queue_item(). Note that this queue number
746 is only valid for about five minutes after the job com‐
747 pletes, so you should get/poll the queue information as
748 soon as possible to determine the job’s URL.
749
750 Parameters
751
752 • name – name of job
753
754 • parameters – parameters for job, or None, dict
755
756 • token – Jenkins API token
757
758 Returns
759 int queue item
760
761 run_script(script, node=None)
762 Execute a groovy script on the jenkins master or on a
763 node if specified..
764
765 Parameters
766
767 • script – The groovy script, string
768
769 • node – Node to run the script on, defaults to
770 None (master).
771
772 Returns
773 The result of the script run.
774
775 Example::
776
777 >>> info = server.run_script("println(Jenkins.instance.pluginManager.plugins)")
778 >>> print(info)
779 u'[Plugin:windows-slaves, Plugin:ssh-slaves, Plugin:translation,
780 Plugin:cvs, Plugin:nodelabelparameter, Plugin:external-monitor-job,
781 Plugin:mailer, Plugin:jquery, Plugin:antisamy-markup-formatter,
782 Plugin:maven-plugin, Plugin:pam-auth]'
783
784 install_plugin(name, include_dependencies=True)
785 Install a plugin and its dependencies from the Jenkins
786 public repository at
787 http://repo.jenkins-ci.org/repo/org/jenkins-ci/plugins
788
789 Parameters
790
791 • name – The plugin short name, string
792
793 • include_dependencies – Install the plugin’s de‐
794 pendencies, bool
795
796 Returns
797 Whether a Jenkins restart is required, bool
798
799 Example::
800
801 >>> info = server.install_plugin("jabber")
802 >>> print(info)
803 True
804
805 stop_build(name, number)
806 Stop a running Jenkins build.
807
808 Parameters
809
810 • name – Name of Jenkins job, str
811
812 • number – Jenkins build number for the job, int
813
814 delete_build(name, number)
815 Delete a Jenkins build.
816
817 Parameters
818
819 • name – Name of Jenkins job, str
820
821 • number – Jenkins build number for the job, int
822
823 wipeout_job_workspace(name)
824 Wipe out workspace for given Jenkins job.
825
826 Parameters
827 name – Name of Jenkins job, str
828
829 get_running_builds()
830 Return list of running builds.
831
832 Each build is a dict with keys ‘name’, ‘number’, ‘url’,
833 ‘node’, and ‘executor’.
834
835 Returns
836 List of builds, [ { str: str, str: int, str:str,
837 str: str, str: int} ]
838
839 Example::
840
841 >>> builds = server.get_running_builds()
842 >>> print(builds)
843 [{'node': 'foo-slave', 'url': 'https://localhost/job/test/15/',
844 'executor': 0, 'name': 'test', 'number': 15}]
845
846 get_nodes(depth=0)
847 Get a list of nodes connected to the Master
848
849 Each node is a dict with keys ‘name’ and ‘offline’
850
851 Returns
852 List of nodes, [ { str: str, str: bool} ]
853
854 get_node_info(name, depth=0)
855 Get node information dictionary
856
857 Parameters
858
859 • name – Node name, str
860
861 • depth – JSON depth, int
862
863 Returns
864 Dictionary of node info, dict
865
866 node_exists(name)
867 Check whether a node exists
868
869 Parameters
870 name – Name of Jenkins node, str
871
872 Returns
873 True if Jenkins node exists
874
875 assert_node_exists(name, exception_message='node[%s] does not
876 exist')
877 Raise an exception if a node does not exist
878
879 Parameters
880
881 • name – Name of Jenkins node, str
882
883 • exception_message – Message to use for the ex‐
884 ception. Formatted with name
885
886 Throws JenkinsException whenever the node does not exist
887
888 delete_node(name)
889 Delete Jenkins node permanently.
890
891 Parameters
892 name – Name of Jenkins node, str
893
894 disable_node(name, msg='')
895 Disable a node
896
897 Parameters
898
899 • name – Jenkins node name, str
900
901 • msg – Offline message, str
902
903 enable_node(name)
904 Enable a node
905
906 Parameters
907 name – Jenkins node name, str
908
909 create_node(name, numExecutors=2, nodeDescription=None, re‐
910 moteFS='/var/lib/jenkins', labels=None, exclusive=False,
911 launcher='hudson.slaves.CommandLauncher', launcher_params={})
912 Create a node
913
914 Parameters
915
916 • name – name of node to create, str
917
918 • numExecutors – number of executors for node, int
919
920 • nodeDescription – Description of node, str
921
922 • remoteFS – Remote filesystem location to use,
923 str
924
925 • labels – Labels to associate with node, str
926
927 • exclusive – Use this node for tied jobs only,
928 bool
929
930 • launcher – The launch method for the slave,
931 jenkins.LAUNCHER_COMMAND, jenk‐
932 ins.LAUNCHER_SSH, jenkins.LAUNCHER_JNLP, jenk‐
933 ins.LAUNCHER_WINDOWS_SERVICE
934
935 • launcher_params – Additional parameters for the
936 launcher, dict
937
938 get_node_config(name)
939 Get the configuration for a node.
940
941 Parameters
942 name – Jenkins node name, str
943
944 reconfig_node(name, config_xml)
945 Change the configuration for an existing node.
946
947 Parameters
948
949 • name – Jenkins node name, str
950
951 • config_xml – New XML configuration, str
952
953 get_build_console_output(name, number)
954 Get build console text.
955
956 Parameters
957
958 • name – Job name, str
959
960 • number – Build number, int
961
962 Returns
963 Build console output, str
964
965 get_view_name(name)
966 Return the name of a view using the API.
967
968 That is roughly an identity method which can be used to
969 quickly verify a view exists or is accessible without
970 causing too much stress on the server side.
971
972 Parameters
973 name – View name, str
974
975 Returns
976 Name of view or None
977
978 assert_view_exists(name, exception_message='view[%s] does not
979 exist')
980 Raise an exception if a view does not exist
981
982 Parameters
983
984 • name – Name of Jenkins view, str
985
986 • exception_message – Message to use for the ex‐
987 ception. Formatted with name
988
989 Throws JenkinsException whenever the view does not exist
990
991 view_exists(name)
992 Check whether a view exists
993
994 Parameters
995 name – Name of Jenkins view, str
996
997 Returns
998 True if Jenkins view exists
999
1000 get_views()
1001 Get list of views running.
1002
1003 Each view is a dictionary with ‘name’ and ‘url’ keys.
1004
1005 Returns
1006 list of views, [ { str: str} ]
1007
1008 delete_view(name)
1009 Delete Jenkins view permanently.
1010
1011 Parameters
1012 name – Name of Jenkins view, str
1013
1014 create_view(name, config_xml)
1015 Create a new Jenkins view
1016
1017 Parameters
1018
1019 • name – Name of Jenkins view, str
1020
1021 • config_xml – config file text, str
1022
1023 reconfig_view(name, config_xml)
1024 Change configuration of existing Jenkins view.
1025
1026 To create a new view, see Jenkins.create_view().
1027
1028 Parameters
1029
1030 • name – Name of Jenkins view, str
1031
1032 • config_xml – New XML configuration, str
1033
1034 get_view_config(name)
1035 Get configuration of existing Jenkins view.
1036
1037 Parameters
1038 name – Name of Jenkins view, str
1039
1040 Returns
1041 view configuration (XML format)
1042
1043 get_promotion_name(name, job_name)
1044 Return the name of a promotion using the API.
1045
1046 That is roughly an identity method which can be used to
1047 quickly verify a promotion exists for a job or is acces‐
1048 sible without causing too much stress on the server side.
1049
1050 Parameters
1051
1052 • name – Promotion name, str
1053
1054 • job_name – Job name, str
1055
1056 Returns
1057 Name of promotion or None
1058
1059 assert_promotion_exists(name, job_name, exception_message='pro‐
1060 motion[%s] does not exist for job[%s]')
1061 Raise an exception if a job lacks a promotion
1062
1063 Parameters
1064
1065 • name – Name of Jenkins promotion, str
1066
1067 • job_name – Job name, str
1068
1069 • exception_message – Message to use for the ex‐
1070 ception. Formatted with name and job_name
1071
1072 Throws JenkinsException whenever the promotion does not
1073 exist on a job
1074
1075 promotion_exists(name, job_name)
1076 Check whether a job has a certain promotion
1077
1078 Parameters
1079
1080 • name – Name of Jenkins promotion, str
1081
1082 • job_name – Job name, str
1083
1084 Returns
1085 True if Jenkins promotion exists
1086
1087 get_promotions_info(job_name, depth=0)
1088 Get promotion information dictionary of a job
1089
1090 Parameters
1091
1092 • job_name – job_name, str
1093
1094 • depth – JSON depth, int
1095
1096 Returns
1097 Dictionary of promotion info, dict
1098
1099 get_promotions(job_name)
1100 Get list of promotions running.
1101
1102 Each promotion is a dictionary with ‘name’ and ‘url’
1103 keys.
1104
1105 Parameters
1106 job_name – Job name, str
1107
1108 Returns
1109 list of promotions, [ { str: str} ]
1110
1111 delete_promotion(name, job_name)
1112 Delete Jenkins promotion permanently.
1113
1114 Parameters
1115
1116 • name – Name of Jenkins promotion, str
1117
1118 • job_name – Job name, str
1119
1120 create_promotion(name, job_name, config_xml)
1121 Create a new Jenkins promotion
1122
1123 Parameters
1124
1125 • name – Name of Jenkins promotion, str
1126
1127 • job_name – Job name, str
1128
1129 • config_xml – config file text, str
1130
1131 reconfig_promotion(name, job_name, config_xml)
1132 Change configuration of existing Jenkins promotion.
1133
1134 To create a new promotion, see
1135 Jenkins.create_promotion().
1136
1137 Parameters
1138
1139 • name – Name of Jenkins promotion, str
1140
1141 • job_name – Job name, str
1142
1143 • config_xml – New XML configuration, str
1144
1145 get_promotion_config(name, job_name)
1146 Get configuration of existing Jenkins promotion.
1147
1148 Parameters
1149
1150 • name – Name of Jenkins promotion, str
1151
1152 • job_name – Job name, str
1153
1154 Returns
1155 promotion configuration (XML format)
1156
1157 assert_folder(name, exception_message='job[%s] is not a folder')
1158 Raise an exception if job is not Cloudbees Folder
1159
1160 Parameters
1161
1162 • name – Name of job, str
1163
1164 • exception_message – Message to use for the ex‐
1165 ception.
1166
1167 Throws JenkinsException whenever the job is not Cloudbees
1168 Folder
1169
1170 is_folder(name)
1171 Check whether a job is Cloudbees Folder
1172
1173 Parameters
1174 name – Job name, str
1175
1176 Returns
1177 True if job is folder, False otherwise
1178
1179 assert_credential_exists(name, folder_name, domain_name='_', ex‐
1180 ception_message='credential[%s] does not exist in the domain[%s]
1181 of [%s]')
1182 Raise an exception if credential does not exist in domain
1183 of folder
1184
1185 Parameters
1186
1187 • name – Name of credential, str
1188
1189 • folder_name – Folder name, str
1190
1191 • domain_name – Domain name, default is ‘_’, str
1192
1193 • exception_message – Message to use for the ex‐
1194 ception. Formatted with name, domain_name, and
1195 folder_name
1196
1197 Throws JenkinsException whenever the credentail does not
1198 exist in domain of folder
1199
1200 credential_exists(name, folder_name, domain_name='_')
1201 Check whether a credentail exists in domain of folder
1202
1203 Parameters
1204
1205 • name – Name of credentail, str
1206
1207 • folder_name – Folder name, str
1208
1209 • domain_name – Domain name, default is ‘_’, str
1210
1211 Returns
1212 True if credentail exists, False otherwise
1213
1214 get_credential_info(name, folder_name, domain_name='_')
1215 Get credential information dictionary in domain of folder
1216
1217 Parameters
1218
1219 • name – Name of credentail, str
1220
1221 • folder_name – folder_name, str
1222
1223 • domain_name – Domain name, default is ‘_’, str
1224
1225 Returns
1226 Dictionary of credential info, dict
1227
1228 get_credential_config(name, folder_name, domain_name='_')
1229 Get configuration of credential in domain of folder.
1230
1231 Parameters
1232
1233 • name – Name of credentail, str
1234
1235 • folder_name – Folder name, str
1236
1237 • domain_name – Domain name, default is ‘_’, str
1238
1239 Returns
1240 Credential configuration (XML format)
1241
1242 create_credential(folder_name, config_xml, domain_name='_')
1243 Create credentail in domain of folder
1244
1245 Parameters
1246
1247 • folder_name – Folder name, str
1248
1249 • config_xml – New XML configuration, str
1250
1251 • domain_name – Domain name, default is ‘_’, str
1252
1253 delete_credential(name, folder_name, domain_name='_')
1254 Delete credential from domain of folder
1255
1256 Parameters
1257
1258 • name – Name of credentail, str
1259
1260 • folder_name – Folder name, str
1261
1262 • domain_name – Domain name, default is ‘_’, str
1263
1264 reconfig_credential(folder_name, config_xml, domain_name='_')
1265 Reconfig credential with new config in domain of folder
1266
1267 Parameters
1268
1269 • folder_name – Folder name, str
1270
1271 • config_xml – New XML configuration, str
1272
1273 • domain_name – Domain name, default is ‘_’, str
1274
1275 list_credentials(folder_name, domain_name='_')
1276 List credentials in domain of folder
1277
1278 Parameters
1279
1280 • folder_name – Folder name, str
1281
1282 • domain_name – Domain name, default is ‘_’, str
1283
1284 Returns
1285 Credentials list, list
1286
1287 quiet_down()
1288 Prepare Jenkins for shutdown.
1289
1290 No new builds will be started allowing running builds to
1291 complete prior to shutdown of the server.
1292
1293 wait_for_normal_op(timeout)
1294 Wait for jenkins to enter normal operation mode.
1295
1296 Parameters
1297 timeout – number of seconds to wait, int Note this
1298 is not the same as the connection timeout set via
1299 __init__ as that controls the socket timeout. In‐
1300 stead this is how long to wait until the status
1301 returned.
1302
1303 Returns
1304 True if Jenkins became ready in time, False other‐
1305 wise.
1306
1307 Setting timeout to be less than the configured connection
1308 timeout may result in this waiting for at least the con‐
1309 nection timeout length of time before returning. It is
1310 recommended that the timeout here should be at least as
1311 long as any set connection timeout.
1312
1313 class jenkins.plugins.Plugin(*args, **kwargs)
1314 Dictionary object containing plugin metadata.
1315
1316 Populates dictionary using json object input.
1317
1318 accepts same arguments as python dict class.
1319
1320 class jenkins.plugins.PluginVersion(version)
1321 Class providing comparison capabilities for plugin versions.
1322
1323 Parse plugin version and store it for comparison.
1324
1326 The python-jenkins library allows management of a Jenkins server
1327 through the Jenkins REST endpoints. Below are examples to get you
1328 started using the library. If you need further help take a look at the
1329 api docs for more details.
1330
1331 Example 1: Get version of Jenkins
1332 This is an example showing how to connect to a Jenkins instance and re‐
1333 trieve the Jenkins server version.
1334
1335 import jenkins
1336
1337 server = jenkins.Jenkins('http://localhost:8080', username='myuser', password='mypassword')
1338 user = server.get_whoami()
1339 version = server.get_version()
1340 print('Hello %s from Jenkins %s' % (user['fullName'], version))
1341
1342 The above code prints the fullName attribute of the user and the ver‐
1343 sion of the Jenkins master running on ‘localhost:8080’. For example, it
1344 may print “Hello John from Jenkins 2.0”.
1345
1346 From Jenkins version 1.426 onward you can specify an API token instead
1347 of your real password while authenticating the user against the Jenkins
1348 instance. Refer to the Jenkins Authentication wiki for details about
1349 how you can generate an API token. Once you have an API token you can
1350 pass the API token instead of a real password while creating a Jenkins
1351 instance.
1352
1353 Example 2: Logging into Jenkins using kerberos
1354 Kerberos support is only enabled if you have “kerberos” python package
1355 installed. You can install the “kerberos” package from PyPI using the
1356 obvious pip command.
1357
1358 pip install kerberos
1359
1360 NOTE:
1361 This might require python header files as well as kerberos header
1362 files.
1363
1364 If you have “kerberos” python package installed, python-jenkins tries
1365 to authenticate using kerberos automatically when the Jenkins server
1366 replies “401 Unauthorized” and indicates it supports kerberos. That
1367 is, kerberos authentication should work automagically. For a quick
1368 test, just try the following.
1369
1370 import jenkins
1371
1372 server = jenkins.Jenkins('http://localhost:8080')
1373 print server.jobs_count()
1374
1375 NOTE:
1376 Jenkins as such does not support kerberos, it needs to be supported
1377 by the Servlet container or a reverse proxy sitting in front of
1378 Jenkins.
1379
1380 Example 3: Working with Jenkins Jobs
1381 This is an example showing how to create, configure and delete Jenkins
1382 jobs.
1383
1384 server.create_job('empty', jenkins.EMPTY_CONFIG_XML)
1385 jobs = server.get_jobs()
1386 print jobs
1387 my_job = server.get_job_config('cool-job')
1388 print(my_job) # prints XML configuration
1389 server.build_job('empty')
1390 server.disable_job('empty')
1391 server.copy_job('empty', 'empty_copy')
1392 server.enable_job('empty_copy')
1393 server.reconfig_job('empty_copy', jenkins.RECONFIG_XML)
1394
1395 server.delete_job('empty')
1396 server.delete_job('empty_copy')
1397
1398 # build a parameterized job
1399 # requires creating and configuring the api-test job to accept 'param1' & 'param2'
1400 server.build_job('api-test', {'param1': 'test value 1', 'param2': 'test value 2'})
1401 last_build_number = server.get_job_info('api-test')['lastCompletedBuild']['number']
1402 build_info = server.get_build_info('api-test', last_build_number)
1403 print build_info
1404
1405 # get all jobs from the specific view
1406 jobs = server.get_jobs(view_name='View Name')
1407 print jobs
1408
1409 Example 4: Working with Jenkins Views
1410 This is an example showing how to create, configure and delete Jenkins
1411 views.
1412
1413 server.create_view('EMPTY', jenkins.EMPTY_VIEW_CONFIG_XML)
1414 view_config = server.get_view_config('EMPTY')
1415 views = server.get_views()
1416 server.delete_view('EMPTY')
1417 print views
1418
1419 Example 5: Working with Jenkins Plugins
1420 This is an example showing how to retrieve Jenkins plugins information.
1421
1422 plugins = server.get_plugins_info()
1423 print plugins
1424
1425 The above example will print a dictionary containing all the plugins
1426 that are installed on the Jenkins server. An example of what you can
1427 expect from the get_plugins_info() method is documented in the api doc.
1428
1429 Example 6: Working with Jenkins Nodes
1430 This is an example showing how to add, configure, enable and delete
1431 Jenkins nodes.
1432
1433 server.create_node('slave1')
1434 nodes = get_nodes()
1435 print nodes
1436 node_config = server.get_node_info('slave1')
1437 print node_config
1438 server.disable_node('slave1')
1439 server.enable_node('slave1')
1440
1441 # create node with parameters
1442 params = {
1443 'port': '22',
1444 'username': 'juser',
1445 'credentialsId': '10f3a3c8-be35-327e-b60b-a3e5edb0e45f',
1446 'host': 'my.jenkins.slave1'
1447 }
1448 server.create_node(
1449 'slave1',
1450 nodeDescription='my test slave',
1451 remoteFS='/home/juser',
1452 labels='precise',
1453 exclusive=True,
1454 launcher=jenkins.LAUNCHER_SSH,
1455 launcher_params=params)
1456
1457 Example 7: Working with Jenkins Build Queue
1458 This is an example showing how to retrieve information on the Jenkins
1459 queue.
1460
1461 server.build_job('foo')
1462 queue_info = server.get_queue_info()
1463 id = queue_info[0].get('id')
1464 server.cancel_queue(id)
1465
1466 Example 8: Working with Jenkins Cloudbees Folders
1467 Requires the Cloudbees Folders Plugin for Jenkins.
1468
1469 This is an example showing how to create, configure and delete Jenkins
1470 folders.
1471
1472 server.create_job('folder', jenkins.EMPTY_FOLDER_XML)
1473 server.create_job('folder/empty', jenkins.EMPTY_FOLDER_XML)
1474 server.copy_job('folder/empty', 'folder/empty_copy')
1475 server.delete_job('folder/empty_copy')
1476 server.delete_job('folder')
1477
1478 Example 9: Updating Next Build Number
1479 Requires the Next Build Number Plugin for Jenkins.
1480
1481 This is an example showing how to update the next build number for a
1482 Jenkins job.
1483
1484 next_bn = server.get_job_info('job_name')['nextBuildNumber']
1485 server.set_next_build_number('job_name', next_bn + 50)
1486
1487 Example 9: Working with Build Promotions
1488 Requires the Promoted Builds Plugin for Jenkins.
1489
1490 This is an example showing how to create, configure and delete a promo‐
1491 tion process for an existing job.
1492
1493 The job in this example is named prom_job and it needs to have this
1494 config xml snippet before creating the promotion:
1495
1496 <properties>
1497 <hudson.plugins.promoted__builds.JobPropertyImpl>
1498 <activeProcessNames>
1499 <string>prom_name</string>
1500 </activeProcessNames>
1501 </hudson.plugins.promoted__builds.JobPropertyImpl>
1502 </properties>
1503
1504 where prom_name is the name of the promotion that will get added to the
1505 job.
1506
1507 server.create_promotion('prom_name', 'prom_job', jenkins.EMPTY_PROMO_CONFIG_XML)
1508 server.promotion_exists('prom_name', 'prom_job')
1509 print server.get_promotions('prom_job')
1510
1511 server.reconfig_promotion('prom_name', 'prom_job', jenkins.PROMO_RECONFIG_XML)
1512 print server.get_promotion_config('prom_name', 'prom_job')
1513
1514 server.delete_promotion('prom_name', 'prom_job')
1515
1516 Example 10: Waiting for Jenkins to be ready
1517 It is possible to ask the API to wait for Jenkins to be ready with a
1518 given timeout. This can be used to aid launching of Jenkins and then
1519 waiting for the REST API to be responsive before continuing with subse‐
1520 quent configuration.
1521
1522 # timeout here is the socket connection timeout, for each connection
1523 # attempt it will wait at most 5 seconds before assuming there is
1524 # nothing listening. Useful where firewalls may black hole connections.
1525 server = jenkins.Jenkins('http://localhost:8080', timeout=5)
1526
1527 # wait for at least 30 seconds for Jenkins to be ready
1528 if server.wait_for_normal_op(30):
1529 # actions once running
1530 ...
1531 else:
1532 print("Jenkins failed to be ready in sufficient time")
1533 exit 2
1534
1535 Note that the timeout arg to jenkins.Jenkins() is the socket connection
1536 timeout. If you set this to be more than the timeout value passed to
1537 wait_for_normal_op(), then in cases where the underlying connection is
1538 not rejected (firewall black-hole, or slow connection) then
1539 wait_for_normal_op() may wait at least the connection timeout, or a
1540 multiple of it where multiple connection attempts are made. A connec‐
1541 tion timeout of 5 seconds and a wait timeout of 8 will result in poten‐
1542 tially waiting 10 seconds if both connections attempts do not get re‐
1543 sponses.
1544
1546 The module is known to pip and Debian-based distributions as
1547 python-jenkins.
1548
1549 pip:
1550
1551 pip install python-jenkins
1552
1553 easy_install:
1554
1555 easy_install python-jenkins
1556
1557 The module has been packaged since Ubuntu Oneiric (11.10):
1558
1559 apt-get install python-jenkins
1560
1561 And on Fedora 19 and later:
1562
1563 yum install python-jenkins
1564
1565 For development:
1566
1567 python setup.py develop
1568
1569 Documentation
1570 Documentation is included in the doc folder. To generate docs locally
1571 execute the command:
1572
1573 tox -e docs
1574
1575 The generated documentation is then available under doc/build/html/in‐
1576 dex.html.
1577
1578 Unit Tests
1579 Unit tests have been included and are in the tests folder. We recently
1580 started including unit tests as examples in our documentation so to
1581 keep the examples up to date it is very important that we include unit
1582 tests for every module. To run the unit tests, execute the command:
1583
1584 tox -e py27
1585
1586 • Note: View tox.ini to run tests on other versions of Python.
1587
1588 Due to how the tests are split up into a dedicated class per API
1589 method, it is possible to execute tests against a single API at a time.
1590 To execute the tests for the Jenkins.get_version() API execute the com‐
1591 mand:
1592
1593 tox -e py27 -- tests.test_version.JenkinsVersionTest
1594
1595 For further details on how to list tests available and different ways
1596 to execute them, see https://wiki.openstack.org/wiki/Testr.
1597
1598 Test Coverage
1599 To measure test coverage, execute the command:
1600
1601 tox -e cover
1602
1603 • genindex
1604
1605 • modindex
1606
1607 • search
1608
1610 Ken Conley, James Page, Tully Foote, Matthew Gertner
1611
1613 2021, Willow Garage
1614
1615
1616
1617
16181.7.0 Jan 27, 2021 PYTHONJENKINS(1)