Python Jenkins
Python Jenkins
Python Jenkins
Release 1.8.0
1 README 1
1.1 Developers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Writing a patch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Installing without setup.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2 Contents 3
2.1 API reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 Using Python-Jenkins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.2.1 Example 1: Get version of Jenkins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.2.2 Example 2: Logging into Jenkins using kerberos . . . . . . . . . . . . . . . . . . . . . . . 20
2.2.3 Example 3: Working with Jenkins Jobs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.2.4 Example 4: Working with Jenkins Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.2.5 Example 5: Working with Jenkins Plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.2.6 Example 6: Working with Jenkins Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.2.7 Example 7: Working with Jenkins Build Queue . . . . . . . . . . . . . . . . . . . . . . . . 22
2.2.8 Example 8: Working with Jenkins Cloudbees Folders . . . . . . . . . . . . . . . . . . . . . 22
2.2.9 Example 9: Updating Next Build Number . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.2.10 Example 9: Working with Build Promotions . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.2.11 Example 10: Waiting for Jenkins to be ready . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.3 Installing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.3.1 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.3.2 Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.3.3 Test Coverage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Index 29
i
ii
CHAPTER 1
README
Python Jenkins is a python wrapper for the Jenkins REST API which aims to provide a more conventionally pythonic
way of controlling a Jenkins server. It provides a higher-level API containing a number of convenience functions.
We like to use python-jenkins to automate our Jenkins servers. Here are some of the things you can use it for:
• Create new jobs
• Copy existing jobs
• Delete jobs
• Update jobs
• Get a job’s build information
• Get Jenkins master version information
• Get Jenkins plugin information
• Start a build on a job
• Create nodes
• Enable/Disable nodes
• Get information on nodes
• Create/delete/reconfig views
• Put server in shutdown mode (quiet down)
• List running builds
• Delete builds
• Wipeout job workspace
• Create/delete/update folders1
1 The free Cloudbees Folders Plugin provides support for a subset of the full folders functionality. For the complete capabilities you will need
the paid for version of the plugin.
1
Python Jenkins Documentation, Release 1.8.0
Online documentation:
• http://python-jenkins.readthedocs.org/en/latest/
1.1 Developers
Bug report:
• https://bugs.launchpad.net/python-jenkins
Repository:
• https://opendev.org/jjb/python-jenkins
Cloning:
• git clone https://opendev.org/jjb/python-jenkins
Patches are submitted via Gerrit at:
• https://review.opendev.org/#/q/project:jjb/python-jenkins
Please do not submit GitHub pull requests, they will be automatically closed.
The python-jenkins developers communicate in the #openstack-jjb channel on Freenode’s IRC network.
More details on how you can contribute is available on our wiki at:
• https://docs.opendev.org/opendev/infra-manual/latest/developers.html
Be sure that you lint code before created an code review. The easiest way to do this is to install git pre-commit hooks.
2 The Next Build Number Plugin provides support for setting the next build number.
2 Chapter 1. README
CHAPTER 2
Contents
3
Python Jenkins Documentation, Release 1.8.0
Parameters
• pattern – regex pattern, str
• depth – JSON depth, int
• folder_depth – folder level depth to search int
• folder_depth_per_request – Number of levels to fetch at once, int. See
get_all_jobs().
Returns List of jobs info, list
get_job_name(name)
Return the name of a job using the API.
That is roughly an identity method which can be used to quickly verify a job exists or is accessible without
causing too much stress on the server side.
Parameters name – Job name, str
Returns Name of job or None
debug_job_info(job_name)
Print out job info in more readable format.
jenkins_open(req, add_crumb=True, resolve_auth=True)
Return the HTTP response body from a requests.Request.
Returns str
jenkins_request(req, add_crumb=True, resolve_auth=True)
Utility routine for opening an HTTP request to a Jenkins server.
Parameters
• req – A requests.Request to submit.
• add_crumb – If True, try to add a crumb header to this req before submitting. Defaults
to True.
4 Chapter 2. Contents
Python Jenkins Documentation, Release 1.8.0
Returns dictionary of build env vars, dict or None for workflow jobs, or if InjectEnvVars
plugin not installed
get_build_test_report(name, number, depth=0)
Get test results report.
Parameters
• name – Job name, str
• number – Build number, str (also accepts int)
Returns dictionary of test report results, dict or None if there is no Test Report
get_build_artifact(name, number, artifact)
Get artifacts from job
Parameters
• name – Job name, str
• number – Build number, str (also accepts int)
• artifact – Artifact relative path, str
Returns artifact to download, dict
get_build_stages(name, number)
Get stages info from job
Parameters
• name – Job name, str
• number – Build number, str (also accepts int)
Returns dictionary of stages in the job, dict
get_queue_info()
Returns list of job dictionaries, [dict]
Example::
cancel_queue(id)
Cancel a queued build.
Parameters id – Jenkins job id number for the build, int
get_info(item=”, query=None)
Get information on this Master or item on Master.
This information includes job list and view information and can be used to retreive information on items
such as job folders.
Parameters
• item – item to get information about on this Master
6 Chapter 2. Contents
Python Jenkins Documentation, Release 1.8.0
get_whoami(depth=0)
Get information about the user account that authenticated to Jenkins. This is a simple way to verify that
your credentials are correct.
Returns Information about the current user dict
Example:
>>> me = server.get_whoami()
>>> print me['fullName']
>>> 'John'
get_version()
Get the version of this Master.
Returns This master’s version number str
Example:
get_plugins_info(depth=2)
Get all installed plugins information on this Master.
This method retrieves information about each plugin that is installed on master returning the raw plugin
data in a JSON format.
Deprecated since version 0.4.9: Use get_plugins() instead.
Parameters depth – JSON depth, int
Returns info on all plugins [dict]
Example:
get_plugin_info(name, depth=2)
Get an installed plugin information on this Master.
This method retrieves information about a specific plugin and returns the raw plugin data in a JSON format.
The passed in plugin name (short or long) must be an exact match.
Note: Calling this method will query Jenkins fresh for the information for all plugins on each call. If
you need to retrieve information for multiple plugins it’s recommended to use get_plugins() instead,
which will return a multi key dictionary that can be accessed via either the short or long name of the plugin.
Parameters
• name – Name (short or long) of plugin, str
• depth – JSON depth, int
Returns a specific plugin dict
Example:
get_plugins(depth=2)
Return plugins info using helper class for version comparison
This method retrieves information about all the installed plugins and uses a Plugin helper class to simplify
version comparison. Also uses a multi key dict to allow retrieval via either short or long names.
When printing/dumping the data, the version will transparently return a unicode string, which is exactly
what was previously returned by the API.
Parameters depth – JSON depth, int
Returns info on all plugins [dict]
Example:
>>> j = Jenkins()
>>> info = j.get_plugins()
>>> print(info)
{('gearman-plugin', 'Gearman Plugin'):
{u'backupVersion': None, u'version': u'0.0.4',
u'deleted': False, u'supportsDynamicLoad': u'MAYBE',
u'hasUpdate': True, u'enabled': True, u'pinned': False,
u'downgradable': False, u'dependencies': [], u'url':
u'http://wiki.jenkins-ci.org/display/JENKINS/Gearman+Plugin',
u'longName': u'Gearman Plugin', u'active': True, u'shortName':
u'gearman-plugin', u'bundled': False}, ...}
8 Chapter 2. Contents
Python Jenkins Documentation, Release 1.8.0
If the view_name parameter is present, the list of jobs will be limited to only those configured in the
specified view. In this case, the job dictionary ‘fullname’ key would be equal to the job name.
Parameters
• folder_depth – Number of levels to search, int. By default 0, which will limit search
to toplevel. None disables the limit.
• folder_depth_per_request – Number of levels to fetch at once, int. See
get_all_jobs().
• view_name – Name of a Jenkins view for which to retrieve jobs, str. By default, the
job list is not limited to a specific view.
Returns list of jobs, [{str: str, str: str, str: str, str: str}]
Example:
get_all_jobs(folder_depth=None, folder_depth_per_request=10)
Get list of all jobs recursively to the given folder depth.
Each job is a dictionary with ‘name’, ‘url’, ‘color’ and ‘fullname’ keys.
Parameters
• folder_depth – Number of levels to search, int. By default None, which will search
all levels. 0 limits to toplevel.
• folder_depth_per_request – Number of levels to fetch at once, int. By default
10, which is usually enough to fetch all jobs using a single request and still easily fits into
an HTTP request.
Returns list of jobs, [ { str: str} ]
Note: On instances with many folders it would not be efficient to fetch each folder separately, hence
folder_depth_per_request levels are fetched at once using the tree query parameter:
?tree=jobs[url,color,name,jobs[...,jobs[...,jobs[...,jobs]]]]
If there are more folder levels than the query asks for, Jenkins returns empty1 objects at the deepest level:
copy_job(from_name, to_name)
Copy a Jenkins job.
Will raise an exception whenever the source and destination folder for this jobs won’t be the same.
1 Actually recent Jenkins includes a _class field everywhere, but it’s missing the requested fields.
Parameters
• from_name – Name of Jenkins job to copy from, str
• to_name – Name of Jenkins job to copy to, str
Throws JenkinsException whenever the source and destination folder are not the same
rename_job(from_name, to_name)
Rename an existing Jenkins job
Will raise an exception whenever the source and destination folder for this jobs won’t be the same.
Parameters
• from_name – Name of Jenkins job to rename, str
• to_name – New Jenkins job name, str
Throws JenkinsException whenever the source and destination folder are not the same
delete_job(name)
Delete Jenkins job permanently.
Parameters name – Name of Jenkins job, str
enable_job(name)
Enable Jenkins job.
Parameters name – Name of Jenkins job, str
disable_job(name)
Disable Jenkins job.
To re-enable, call Jenkins.enable_job().
Parameters name – Name of Jenkins job, str
set_next_build_number(name, number)
Set a job’s next build number.
The current next build number is contained within the job information retrieved using Jenkins.
get_job_info(). If the specified next build number is less than the last build number, Jenkins will
ignore the request.
Note that the Next Build Number Plugin must be installed to enable this functionality.
Parameters
• name – Name of Jenkins job, str
• number – Next build number to set, int
Example:
job_exists(name)
Check whether a job exists
Parameters name – Name of Jenkins job, str
Returns True if Jenkins job exists
jobs_count()
Get the number of jobs on the Jenkins server
10 Chapter 2. Contents
Python Jenkins Documentation, Release 1.8.0
Use list of two membered tuples to supply parameters with multi select options.
Parameters
• name – Name of Jenkins job, str
• parameters – parameters for job, or None., dict or list of two membered
tuples
• token – (optional) token for building job, str
Returns URL for building job
build_job(name, parameters=None, token=None)
Trigger build job.
This method returns a queue item number that you can pass to Jenkins.get_queue_item(). Note
that this queue number is only valid for about five minutes after the job completes, so you should get/poll
the queue information as soon as possible to determine the job’s URL.
Parameters
• name – name of job
• parameters – parameters for job, or None, dict
• token – Jenkins API token
Returns int queue item
run_script(script, node=None)
Execute a groovy script on the jenkins master or on a node if specified..
Parameters
• script – The groovy script, string
• node – Node to run the script on, defaults to None (master).
Returns The result of the script run.
Example::
>>> print(info)
u'[Plugin:windows-slaves, Plugin:ssh-slaves, Plugin:translation,
Plugin:cvs, Plugin:nodelabelparameter, Plugin:external-monitor-job,
Plugin:mailer, Plugin:jquery, Plugin:antisamy-markup-formatter,
Plugin:maven-plugin, Plugin:pam-auth]'
install_plugin(name, include_dependencies=True)
Install a plugin and its dependencies from the Jenkins public repository at http://repo.jenkins-ci.org/repo/
org/jenkins-ci/plugins
Parameters
• name – The plugin short name, string
• include_dependencies – Install the plugin’s dependencies, bool
Returns Whether a Jenkins restart is required, bool
Example::
12 Chapter 2. Contents
Python Jenkins Documentation, Release 1.8.0
stop_build(name, number)
Stop a running Jenkins build.
Parameters
• name – Name of Jenkins job, str
• number – Jenkins build number for the job, int
delete_build(name, number)
Delete a Jenkins build.
Parameters
• name – Name of Jenkins job, str
• number – Jenkins build number for the job, int
wipeout_job_workspace(name)
Wipe out workspace for given Jenkins job.
Parameters name – Name of Jenkins job, str
get_running_builds()
Return list of running builds.
Each build is a dict with keys ‘name’, ‘number’, ‘url’, ‘node’, and ‘executor’.
Returns List of builds, [ { str: str, str: int, str:str, str: str,
str: int} ]
Example::
get_nodes(depth=0)
Get a list of nodes connected to the Master
Each node is a dict with keys ‘name’ and ‘offline’
Returns List of nodes, [ { str: str, str: bool} ]
get_node_info(name, depth=0)
Get node information dictionary
Parameters
• name – Node name, str
• depth – JSON depth, int
Returns Dictionary of node info, dict
node_exists(name)
Check whether a node exists
Parameters name – Name of Jenkins node, str
14 Chapter 2. Contents
Python Jenkins Documentation, Release 1.8.0
16 Chapter 2. Contents
Python Jenkins Documentation, Release 1.8.0
Parameters
• name – Name of credential, str
• folder_name – Folder name, str
• domain_name – Domain name, default is ‘_’, str
• exception_message – Message to use for the exception. Formatted with name,
domain_name, and folder_name
Throws JenkinsException whenever the credentail does not exist in domain of folder
credential_exists(name, folder_name, domain_name=’_’)
Check whether a credentail exists in domain of folder
Parameters
• name – Name of credentail, str
• folder_name – Folder name, str
• domain_name – Domain name, default is ‘_’, str
Returns True if credentail exists, False otherwise
get_credential_info(name, folder_name, domain_name=’_’)
Get credential information dictionary in domain of folder
Parameters
• name – Name of credentail, str
• folder_name – folder_name, str
• domain_name – Domain name, default is ‘_’, str
Returns Dictionary of credential info, dict
get_credential_config(name, folder_name, domain_name=’_’)
Get configuration of credential in domain of folder.
Parameters
• name – Name of credentail, str
• folder_name – Folder name, str
• domain_name – Domain name, default is ‘_’, str
Returns Credential configuration (XML format)
create_credential(folder_name, config_xml, domain_name=’_’)
Create credentail in domain of folder
Parameters
• folder_name – Folder name, str
• config_xml – New XML configuration, str
• domain_name – Domain name, default is ‘_’, str
delete_credential(name, folder_name, domain_name=’_’)
Delete credential from domain of folder
Parameters
• name – Name of credentail, str
18 Chapter 2. Contents
Python Jenkins Documentation, Release 1.8.0
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.
This is an example showing how to connect to a Jenkins instance and retrieve the Jenkins server version.
import jenkins
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 ‘local-
host: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.
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
Note: 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()
Note: 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.
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')
(continues on next page)
20 Chapter 2. Contents
Python Jenkins Documentation, Release 1.8.0
server.delete_job('empty')
server.delete_job('empty_copy')
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
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.
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')
server.build_job('foo')
queue_info = server.get_queue_info()
id = queue_info[0].get('id')
server.cancel_queue(id)
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')
next_bn = server.get_job_info('job_name')['nextBuildNumber']
server.set_next_build_number('job_name', next_bn + 50)
22 Chapter 2. Contents
Python Jenkins Documentation, Release 1.8.0
<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.delete_promotion('prom_name', 'prom_job')
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.
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.
2.3 Installing
easy_install:
2.3. Installing 23
Python Jenkins Documentation, Release 1.8.0
easy_install python-jenkins
For development:
2.3.1 Documentation
Documentation is included in the doc folder. To generate docs locally execute the command:
tox -e docs
Unit tests have been included and are in the tests folder. We recently started including unit tests as examples in our
documentation so to keep the examples up to date it is very important that we include unit tests for every module. To
run the unit tests, execute the command:
tox -e py27
For further details on how to list tests available and different ways to execute them, see https://wiki.openstack.org/
wiki/Testr.
tox -e cover
24 Chapter 2. Contents
CHAPTER 3
• genindex
• modindex
• search
25
Python Jenkins Documentation, Release 1.8.0
j
jenkins, 3
jenkins.plugins (Unix, Windows), 19
27
Python Jenkins Documentation, Release 1.8.0
29
Python Jenkins Documentation, Release 1.8.0
L
list_credentials() (jenkins.Jenkins method), 19
M
maybe_add_crumb() (jenkins.Jenkins method), 4
merge_environment_settings() (jenk-
ins.WrappedSession method), 3
N
node_exists() (jenkins.Jenkins method), 13
NotFoundException, 3
P
promotion_exists() (jenkins.Jenkins method), 16
Q
quiet_down() (jenkins.Jenkins method), 19
R
reconfig_credential() (jenkins.Jenkins method),
19
reconfig_job() (jenkins.Jenkins method), 11
reconfig_node() (jenkins.Jenkins method), 14
reconfig_promotion() (jenkins.Jenkins method),
17
reconfig_view() (jenkins.Jenkins method), 15
30 Index