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
119 response.
120
121 exception jenkins.BadHTTPException
122 A special exception to call out the case of a broken HTTP
123 response.
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, time‐
144 out=<object 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
294 installed
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()
387 instead.
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
421 return 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
452 retrieval 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
534 request and still easily fits into an HTTP
535 request.
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
555 requests 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
650 exist')
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
658 exception. 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
670 was 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
794 dependencies, 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
884 exception. 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,
910 remoteFS='/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,
919 int
920
921 · nodeDescription -- Description of node, str
922
923 · remoteFS -- Remote filesystem location to use,
924 str
925
926 · labels -- Labels to associate with node, str
927
928 · exclusive -- Use this node for tied jobs only,
929 bool
930
931 · launcher -- The launch method for the slave,
932 jenkins.LAUNCHER_COMMAND, jenk‐
933 ins.LAUNCHER_SSH, jenkins.LAUNCHER_JNLP, jenk‐
934 ins.LAUNCHER_WINDOWS_SERVICE
935
936 · launcher_params -- Additional parameters for the
937 launcher, dict
938
939 get_node_config(name)
940 Get the configuration for a node.
941
942 Parameters
943 name -- Jenkins node name, str
944
945 reconfig_node(name, config_xml)
946 Change the configuration for an existing node.
947
948 Parameters
949
950 · name -- Jenkins node name, str
951
952 · config_xml -- New XML configuration, str
953
954 get_build_console_output(name, number)
955 Get build console text.
956
957 Parameters
958
959 · name -- Job name, str
960
961 · number -- Build number, int
962
963 Returns
964 Build console output, str
965
966 get_view_name(name)
967 Return the name of a view using the API.
968
969 That is roughly an identity method which can be used to
970 quickly verify a view exists or is accessible without
971 causing too much stress on the server side.
972
973 Parameters
974 name -- View name, str
975
976 Returns
977 Name of view or None
978
979 assert_view_exists(name, exception_message='view[%s] does not
980 exist')
981 Raise an exception if a view does not exist
982
983 Parameters
984
985 · name -- Name of Jenkins view, str
986
987 · exception_message -- Message to use for the
988 exception. Formatted with name
989
990 Throws JenkinsException whenever the view does not exist
991
992 view_exists(name)
993 Check whether a view exists
994
995 Parameters
996 name -- Name of Jenkins view, str
997
998 Returns
999 True if Jenkins view exists
1000
1001 get_views()
1002 Get list of views running.
1003
1004 Each view is a dictionary with 'name' and 'url' keys.
1005
1006 Returns
1007 list of views, [ { str: str} ]
1008
1009 delete_view(name)
1010 Delete Jenkins view permanently.
1011
1012 Parameters
1013 name -- Name of Jenkins view, str
1014
1015 create_view(name, config_xml)
1016 Create a new Jenkins view
1017
1018 Parameters
1019
1020 · name -- Name of Jenkins view, str
1021
1022 · config_xml -- config file text, str
1023
1024 reconfig_view(name, config_xml)
1025 Change configuration of existing Jenkins view.
1026
1027 To create a new view, see Jenkins.create_view().
1028
1029 Parameters
1030
1031 · name -- Name of Jenkins view, str
1032
1033 · config_xml -- New XML configuration, str
1034
1035 get_view_config(name)
1036 Get configuration of existing Jenkins view.
1037
1038 Parameters
1039 name -- Name of Jenkins view, str
1040
1041 Returns
1042 view configuration (XML format)
1043
1044 get_promotion_name(name, job_name)
1045 Return the name of a promotion using the API.
1046
1047 That is roughly an identity method which can be used to
1048 quickly verify a promotion exists for a job or is acces‐
1049 sible without causing too much stress on the server side.
1050
1051 Parameters
1052
1053 · name -- Promotion name, str
1054
1055 · job_name -- Job name, str
1056
1057 Returns
1058 Name of promotion or None
1059
1060 assert_promotion_exists(name, job_name, exception_message='pro‐
1061 motion[%s] does not exist for job[%s]')
1062 Raise an exception if a job lacks a promotion
1063
1064 Parameters
1065
1066 · name -- Name of Jenkins promotion, str
1067
1068 · job_name -- Job name, str
1069
1070 · exception_message -- Message to use for the
1071 exception. Formatted with name and job_name
1072
1073 Throws JenkinsException whenever the promotion does not
1074 exist on a job
1075
1076 promotion_exists(name, job_name)
1077 Check whether a job has a certain promotion
1078
1079 Parameters
1080
1081 · name -- Name of Jenkins promotion, str
1082
1083 · job_name -- Job name, str
1084
1085 Returns
1086 True if Jenkins promotion exists
1087
1088 get_promotions_info(job_name, depth=0)
1089 Get promotion information dictionary of a job
1090
1091 Parameters
1092
1093 · job_name -- job_name, str
1094
1095 · depth -- JSON depth, int
1096
1097 Returns
1098 Dictionary of promotion info, dict
1099
1100 get_promotions(job_name)
1101 Get list of promotions running.
1102
1103 Each promotion is a dictionary with 'name' and 'url'
1104 keys.
1105
1106 Parameters
1107 job_name -- Job name, str
1108
1109 Returns
1110 list of promotions, [ { str: str} ]
1111
1112 delete_promotion(name, job_name)
1113 Delete Jenkins promotion permanently.
1114
1115 Parameters
1116
1117 · name -- Name of Jenkins promotion, str
1118
1119 · job_name -- Job name, str
1120
1121 create_promotion(name, job_name, config_xml)
1122 Create a new Jenkins promotion
1123
1124 Parameters
1125
1126 · name -- Name of Jenkins promotion, str
1127
1128 · job_name -- Job name, str
1129
1130 · config_xml -- config file text, str
1131
1132 reconfig_promotion(name, job_name, config_xml)
1133 Change configuration of existing Jenkins promotion.
1134
1135 To create a new promotion, see
1136 Jenkins.create_promotion().
1137
1138 Parameters
1139
1140 · name -- Name of Jenkins promotion, str
1141
1142 · job_name -- Job name, str
1143
1144 · config_xml -- New XML configuration, str
1145
1146 get_promotion_config(name, job_name)
1147 Get configuration of existing Jenkins promotion.
1148
1149 Parameters
1150
1151 · name -- Name of Jenkins promotion, str
1152
1153 · job_name -- Job name, str
1154
1155 Returns
1156 promotion configuration (XML format)
1157
1158 assert_folder(name, exception_message='job[%s] is not a folder')
1159 Raise an exception if job is not Cloudbees Folder
1160
1161 Parameters
1162
1163 · name -- Name of job, str
1164
1165 · exception_message -- Message to use for the
1166 exception.
1167
1168 Throws JenkinsException whenever the job is not Cloudbees
1169 Folder
1170
1171 is_folder(name)
1172 Check whether a job is Cloudbees Folder
1173
1174 Parameters
1175 name -- Job name, str
1176
1177 Returns
1178 True if job is folder, False otherwise
1179
1180 assert_credential_exists(name, folder_name, domain_name='_',
1181 exception_message='credential[%s] does not exist in the
1182 domain[%s] of [%s]')
1183 Raise an exception if credential does not exist in domain
1184 of folder
1185
1186 Parameters
1187
1188 · name -- Name of credential, str
1189
1190 · folder_name -- Folder name, str
1191
1192 · domain_name -- Domain name, default is '_', str
1193
1194 · exception_message -- Message to use for the
1195 exception. Formatted with name, domain_name,
1196 and folder_name
1197
1198 Throws JenkinsException whenever the credentail does not
1199 exist in domain of folder
1200
1201 credential_exists(name, folder_name, domain_name='_')
1202 Check whether a credentail exists in domain of folder
1203
1204 Parameters
1205
1206 · name -- Name of credentail, str
1207
1208 · folder_name -- Folder name, str
1209
1210 · domain_name -- Domain name, default is '_', str
1211
1212 Returns
1213 True if credentail exists, False otherwise
1214
1215 get_credential_info(name, folder_name, domain_name='_')
1216 Get credential information dictionary in domain of folder
1217
1218 Parameters
1219
1220 · name -- Name of credentail, str
1221
1222 · folder_name -- folder_name, str
1223
1224 · domain_name -- Domain name, default is '_', str
1225
1226 Returns
1227 Dictionary of credential info, dict
1228
1229 get_credential_config(name, folder_name, domain_name='_')
1230 Get configuration of credential in domain of folder.
1231
1232 Parameters
1233
1234 · name -- Name of credentail, str
1235
1236 · folder_name -- Folder name, str
1237
1238 · domain_name -- Domain name, default is '_', str
1239
1240 Returns
1241 Credential configuration (XML format)
1242
1243 create_credential(folder_name, config_xml, domain_name='_')
1244 Create credentail in domain of folder
1245
1246 Parameters
1247
1248 · folder_name -- Folder name, str
1249
1250 · config_xml -- New XML configuration, str
1251
1252 · domain_name -- Domain name, default is '_', str
1253
1254 delete_credential(name, folder_name, domain_name='_')
1255 Delete credential from domain of folder
1256
1257 Parameters
1258
1259 · name -- Name of credentail, str
1260
1261 · folder_name -- Folder name, str
1262
1263 · domain_name -- Domain name, default is '_', str
1264
1265 reconfig_credential(folder_name, config_xml, domain_name='_')
1266 Reconfig credential with new config in domain of folder
1267
1268 Parameters
1269
1270 · folder_name -- Folder name, str
1271
1272 · config_xml -- New XML configuration, str
1273
1274 · domain_name -- Domain name, default is '_', str
1275
1276 list_credentials(folder_name, domain_name='_')
1277 List credentials in domain of folder
1278
1279 Parameters
1280
1281 · folder_name -- Folder name, str
1282
1283 · domain_name -- Domain name, default is '_', str
1284
1285 Returns
1286 Credentials list, list
1287
1288 quiet_down()
1289 Prepare Jenkins for shutdown.
1290
1291 No new builds will be started allowing running builds to
1292 complete prior to shutdown of the server.
1293
1294 wait_for_normal_op(timeout)
1295 Wait for jenkins to enter normal operation mode.
1296
1297 Parameters
1298 timeout -- number of seconds to wait, int Note
1299 this is not the same as the connection timeout set
1300 via __init__ as that controls the socket timeout.
1301 Instead this is how long to wait until the status
1302 returned.
1303
1304 Returns
1305 True if Jenkins became ready in time, False other‐
1306 wise.
1307
1308 Setting timeout to be less than the configured connection
1309 timeout may result in this waiting for at least the con‐
1310 nection timeout length of time before returning. It is
1311 recommended that the timeout here should be at least as
1312 long as any set connection timeout.
1313
1314 class jenkins.plugins.Plugin(*args, **kwargs)
1315 Dictionary object containing plugin metadata.
1316
1317 Populates dictionary using json object input.
1318
1319 accepts same arguments as python dict class.
1320
1321 class jenkins.plugins.PluginVersion(version)
1322 Class providing comparison capabilities for plugin versions.
1323
1324 Parse plugin version and store it for comparison.
1325
1327 The python-jenkins library allows management of a Jenkins server
1328 through the Jenkins REST endpoints. Below are examples to get you
1329 started using the library. If you need further help take a look at the
1330 api docs for more details.
1331
1332 Example 1: Get version of Jenkins
1333 This is an example showing how to connect to a Jenkins instance and
1334 retrieve the Jenkins server version.
1335
1336 import jenkins
1337
1338 server = jenkins.Jenkins('http://localhost:8080', username='myuser', password='mypassword')
1339 user = server.get_whoami()
1340 version = server.get_version()
1341 print('Hello %s from Jenkins %s' % (user['fullName'], version))
1342
1343 The above code prints the fullName attribute of the user and the ver‐
1344 sion of the Jenkins master running on 'localhost:8080'. For example, it
1345 may print "Hello John from Jenkins 2.0".
1346
1347 From Jenkins version 1.426 onward you can specify an API token instead
1348 of your real password while authenticating the user against the Jenkins
1349 instance. Refer to the Jenkins Authentication wiki for details about
1350 how you can generate an API token. Once you have an API token you can
1351 pass the API token instead of a real password while creating a Jenkins
1352 instance.
1353
1354 Example 2: Logging into Jenkins using kerberos
1355 Kerberos support is only enabled if you have "kerberos" python package
1356 installed. You can install the "kerberos" package from PyPI using the
1357 obvious pip command.
1358
1359 pip install kerberos
1360
1361 NOTE:
1362 This might require python header files as well as kerberos header
1363 files.
1364
1365 If you have "kerberos" python package installed, python-jenkins tries
1366 to authenticate using kerberos automatically when the Jenkins server
1367 replies "401 Unauthorized" and indicates it supports kerberos. That
1368 is, kerberos authentication should work automagically. For a quick
1369 test, just try the following.
1370
1371 import jenkins
1372
1373 server = jenkins.Jenkins('http://localhost:8080')
1374 print server.jobs_count()
1375
1376 NOTE:
1377 Jenkins as such does not support kerberos, it needs to be supported
1378 by the Servlet container or a reverse proxy sitting in front of
1379 Jenkins.
1380
1381 Example 3: Working with Jenkins Jobs
1382 This is an example showing how to create, configure and delete Jenkins
1383 jobs.
1384
1385 server.create_job('empty', jenkins.EMPTY_CONFIG_XML)
1386 jobs = server.get_jobs()
1387 print jobs
1388 my_job = server.get_job_config('cool-job')
1389 print(my_job) # prints XML configuration
1390 server.build_job('empty')
1391 server.disable_job('empty')
1392 server.copy_job('empty', 'empty_copy')
1393 server.enable_job('empty_copy')
1394 server.reconfig_job('empty_copy', jenkins.RECONFIG_XML)
1395
1396 server.delete_job('empty')
1397 server.delete_job('empty_copy')
1398
1399 # build a parameterized job
1400 # requires creating and configuring the api-test job to accept 'param1' & 'param2'
1401 server.build_job('api-test', {'param1': 'test value 1', 'param2': 'test value 2'})
1402 last_build_number = server.get_job_info('api-test')['lastCompletedBuild']['number']
1403 build_info = server.get_build_info('api-test', last_build_number)
1404 print build_info
1405
1406 # get all jobs from the specific view
1407 jobs = server.get_jobs(view_name='View Name')
1408 print jobs
1409
1410 Example 4: Working with Jenkins Views
1411 This is an example showing how to create, configure and delete Jenkins
1412 views.
1413
1414 server.create_view('EMPTY', jenkins.EMPTY_VIEW_CONFIG_XML)
1415 view_config = server.get_view_config('EMPTY')
1416 views = server.get_views()
1417 server.delete_view('EMPTY')
1418 print views
1419
1420 Example 5: Working with Jenkins Plugins
1421 This is an example showing how to retrieve Jenkins plugins information.
1422
1423 plugins = server.get_plugins_info()
1424 print plugins
1425
1426 The above example will print a dictionary containing all the plugins
1427 that are installed on the Jenkins server. An example of what you can
1428 expect from the get_plugins_info() method is documented in the api doc.
1429
1430 Example 6: Working with Jenkins Nodes
1431 This is an example showing how to add, configure, enable and delete
1432 Jenkins nodes.
1433
1434 server.create_node('slave1')
1435 nodes = get_nodes()
1436 print nodes
1437 node_config = server.get_node_info('slave1')
1438 print node_config
1439 server.disable_node('slave1')
1440 server.enable_node('slave1')
1441
1442 # create node with parameters
1443 params = {
1444 'port': '22',
1445 'username': 'juser',
1446 'credentialsId': '10f3a3c8-be35-327e-b60b-a3e5edb0e45f',
1447 'host': 'my.jenkins.slave1'
1448 }
1449 server.create_node(
1450 'slave1',
1451 nodeDescription='my test slave',
1452 remoteFS='/home/juser',
1453 labels='precise',
1454 exclusive=True,
1455 launcher=jenkins.LAUNCHER_SSH,
1456 launcher_params=params)
1457
1458 Example 7: Working with Jenkins Build Queue
1459 This is an example showing how to retrieve information on the Jenkins
1460 queue.
1461
1462 server.build_job('foo')
1463 queue_info = server.get_queue_info()
1464 id = queue_info[0].get('id')
1465 server.cancel_queue(id)
1466
1467 Example 8: Working with Jenkins Cloudbees Folders
1468 Requires the Cloudbees Folders Plugin for Jenkins.
1469
1470 This is an example showing how to create, configure and delete Jenkins
1471 folders.
1472
1473 server.create_job('folder', jenkins.EMPTY_FOLDER_XML)
1474 server.create_job('folder/empty', jenkins.EMPTY_FOLDER_XML)
1475 server.copy_job('folder/empty', 'folder/empty_copy')
1476 server.delete_job('folder/empty_copy')
1477 server.delete_job('folder')
1478
1479 Example 9: Updating Next Build Number
1480 Requires the Next Build Number Plugin for Jenkins.
1481
1482 This is an example showing how to update the next build number for a
1483 Jenkins job.
1484
1485 next_bn = server.get_job_info('job_name')['nextBuildNumber']
1486 server.set_next_build_number('job_name', next_bn + 50)
1487
1488 Example 9: Working with Build Promotions
1489 Requires the Promoted Builds Plugin for Jenkins.
1490
1491 This is an example showing how to create, configure and delete a promo‐
1492 tion process for an existing job.
1493
1494 The job in this example is named prom_job and it needs to have this
1495 config xml snippet before creating the promotion:
1496
1497 <properties>
1498 <hudson.plugins.promoted__builds.JobPropertyImpl>
1499 <activeProcessNames>
1500 <string>prom_name</string>
1501 </activeProcessNames>
1502 </hudson.plugins.promoted__builds.JobPropertyImpl>
1503 </properties>
1504
1505 where prom_name is the name of the promotion that will get added to the
1506 job.
1507
1508 server.create_promotion('prom_name', 'prom_job', jenkins.EMPTY_PROMO_CONFIG_XML)
1509 server.promotion_exists('prom_name', 'prom_job')
1510 print server.get_promotions('prom_job')
1511
1512 server.reconfig_promotion('prom_name', 'prom_job', jenkins.PROMO_RECONFIG_XML)
1513 print server.get_promotion_config('prom_name', 'prom_job')
1514
1515 server.delete_promotion('prom_name', 'prom_job')
1516
1517 Example 10: Waiting for Jenkins to be ready
1518 It is possible to ask the API to wait for Jenkins to be ready with a
1519 given timeout. This can be used to aid launching of Jenkins and then
1520 waiting for the REST API to be responsive before continuing with subse‐
1521 quent configuration.
1522
1523 # timeout here is the socket connection timeout, for each connection
1524 # attempt it will wait at most 5 seconds before assuming there is
1525 # nothing listening. Useful where firewalls may black hole connections.
1526 server = jenkins.Jenkins('http://localhost:8080', timeout=5)
1527
1528 # wait for at least 30 seconds for Jenkins to be ready
1529 if server.wait_for_normal_op(30):
1530 # actions once running
1531 ...
1532 else:
1533 print("Jenkins failed to be ready in sufficient time")
1534 exit 2
1535
1536 Note that the timeout arg to jenkins.Jenkins() is the socket connection
1537 timeout. If you set this to be more than the timeout value passed to
1538 wait_for_normal_op(), then in cases where the underlying connection is
1539 not rejected (firewall black-hole, or slow connection) then
1540 wait_for_normal_op() may wait at least the connection timeout, or a
1541 multiple of it where multiple connection attempts are made. A connec‐
1542 tion timeout of 5 seconds and a wait timeout of 8 will result in poten‐
1543 tially waiting 10 seconds if both connections attempts do not get
1544 responses.
1545
1547 The module is known to pip and Debian-based distributions as
1548 python-jenkins.
1549
1550 pip:
1551
1552 pip install python-jenkins
1553
1554 easy_install:
1555
1556 easy_install python-jenkins
1557
1558 The module has been packaged since Ubuntu Oneiric (11.10):
1559
1560 apt-get install python-jenkins
1561
1562 And on Fedora 19 and later:
1563
1564 yum install python-jenkins
1565
1566 For development:
1567
1568 python setup.py develop
1569
1570 Documentation
1571 Documentation is included in the doc folder. To generate docs locally
1572 execute the command:
1573
1574 tox -e docs
1575
1576 The generated documentation is then available under
1577 doc/build/html/index.html.
1578
1579 Unit Tests
1580 Unit tests have been included and are in the tests folder. We recently
1581 started including unit tests as examples in our documentation so to
1582 keep the examples up to date it is very important that we include unit
1583 tests for every module. To run the unit tests, execute the command:
1584
1585 tox -e py27
1586
1587 · Note: View tox.ini to run tests on other versions of Python.
1588
1589 Due to how the tests are split up into a dedicated class per API
1590 method, it is possible to execute tests against a single API at a time.
1591 To execute the tests for the Jenkins.get_version() API execute the com‐
1592 mand:
1593
1594 tox -e py27 -- tests.test_version.JenkinsVersionTest
1595
1596 For further details on how to list tests available and different ways
1597 to execute them, see https://wiki.openstack.org/wiki/Testr.
1598
1599 Test Coverage
1600 To measure test coverage, execute the command:
1601
1602 tox -e cover
1603
1604 · genindex
1605
1606 · modindex
1607
1608 · search
1609
1611 Ken Conley, James Page, Tully Foote, Matthew Gertner
1612
1614 2020, Willow Garage
1615
1616
1617
1618
16191.7.0 Jul 29, 2020 PYTHONJENKINS(1)