pythonjenkins(1)
NAME
pythonjenkins – Python Jenkins Documentation
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
- •
- and many more..
- •
- http://python-jenkins.readthedocs.org/en/latest/
To install:
$ sudo python setup.py install
Online documentation:
DEVELOPERS
Bug report:
- •
- https://bugs.launchpad.net/python-jenkins
- •
- https://git.openstack.org/cgit/stackforge/python-jenkins
- •
- git clone https://git.openstack.org/stackforge/python-jenkins
- •
- https://review.openstack.org/
- •
- http://docs.openstack.org/infra/manual/developers.html
Repository:
Cloning:
Patches are submitted via Gerrit at:
Please do not submit GitHub pull requests, they will be automatically closed.
More details on how you can contribute is available on our wiki at:
WRITING A PATCH
We ask that all code submissions be flake8 clean. The easiest way to do that is to run tox before submitting code for review in Gerrit. It will run flake8 in the same manner as the automated test suite that will run on proposed patchsets.
INSTALLING WITHOUT SETUP.PY
Then install the required python packages using pip:
$ sudo pip install python-jenkins
API REFERENCE
See examples at example
exception jenkins.JenkinsException- General exception type for jenkins-API-related failures.
exception jenkins.NotFoundException- A special exception to call out the case of receiving a 404.
exception jenkins.EmptyResponseException- A special exception to call out the case receiving an empty response.
exception jenkins.BadHTTPException- A special exception to call out the case of a broken HTTP response.
jenkins.auth_headers(username, password)- Simple implementation of HTTP Basic Authentication.
class jenkins.Jenkins(url, username=None, password=None, timeout=<object object at 0x7f5587ade220>)- Create handle to Jenkins instance.
Parameters- •
username— Server username,str- •
password— Server password,str- •
url— URL of Jenkins server,str- •
timeout— Server connection timeout in secs (default: not set),intJenkins.maybe_add_crumb(req)Jenkins.get_job_info(name, depth=0)- Get job information dictionary.
Parameters- •
name— Job name,str- •
depth— JSON depth,intReturns- dictionary of job information
Jenkins.get_job_info_regex(pattern, depth=0)- Get a list of jobs information that contain names which match the regex pattern.
Parameters- •
pattern— regex pattern,str- •
depth— JSON depth,intReturns- List of jobs info,
list Jenkins.get_job_name(name)- Return the name of a job using the API.
Parametersname— Job name,strReturns- Name of job or None
Jenkins.debug_job_info(job_name)- Print out job info in more readable format.
Jenkins.jenkins_open(req, add_crumb=True)- Utility routine for opening an HTTP request to a Jenkins server.
Jenkins.get_build_info(name, number, depth=0)- Get build information dictionary.
Parameters- •
name— Job name,str- •
name— Build number,int- •
depth— JSON depth,intReturns- dictionary of build information,
dict Jenkins.get_queue_info()Returns- list of job dictionaries,
[dict] Example::>>> j = Jenkins() >>> queue_info = j.get_queue_info() >>> print(queue_info[0])
{
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
}Jenkins.cancel_queue(id)- Cancel a queued build.
Parametersid— Jenkins job id number for the build,intJenkins.get_info()- Get information on this Master.
Returns- dictionary of information about Master,
dict Jenkins.get_version()- Get the version of this Master.
Returns- This master’s version number
str Jenkins.get_plugins_info(depth=2)- Get all installed plugins information on this Master.
Parametersdepth— JSON depth,intReturns- info on all plugins
[dict] Jenkins.get_plugin_info(name, depth=2)- Get an installed plugin information on this Master.
Parameters- •
name— Name (short or long) of plugin,str- •
depth— JSON depth,intReturns- a specific plugin
dict Jenkins.get_jobs()- Get list of jobs running.
Returns- list of jobs,
[ { str: str} ] Jenkins.copy_job(from_name, to_name)- Copy a Jenkins job
Parameters- •
from_name— Name of Jenkins job to copy from,str- •
to_name— Name of Jenkins job to copy to,strJenkins.rename_job(from_name, to_name)- Rename an existing Jenkins job
Parameters- •
from_name— Name of Jenkins job to rename,str- •
to_name— New Jenkins job name,strJenkins.delete_job(name)- Delete Jenkins job permanently.
Parametersname— Name of Jenkins job,strJenkins.enable_job(name)- Enable Jenkins job.
Parametersname— Name of Jenkins job,strJenkins.disable_job(name)- Disable Jenkins job.
Parametersname— Name of Jenkins job,strJenkins.job_exists(name)- Check whether a job exists
Parametersname— Name of Jenkins job,strReturnsTrueif Jenkins job existsJenkins.jobs_count()- Get the number of jobs on the Jenkins server
Returns- Total number of jobs,
int Jenkins.assert_job_exists(name, exception_message=’job[%s] does not exist’)- Raise an exception if a job does not exist
Parameters- •
name— Name of Jenkins job,str- •
exception_message— Message to use for the exception. Formatted withnameThrowsJenkinsExceptionwhenever the job does not existJenkins.create_job(name, config_xml)- Create a new Jenkins job
Parameters- •
name— Name of Jenkins job,str- •
config_xml— config file text,strJenkins.get_job_config(name)- Get configuration of existing Jenkins job.
Parametersname— Name of Jenkins job,strReturns- job configuration (XML format)
Jenkins.reconfig_job(name, config_xml)- Change configuration of existing Jenkins job.
Parameters- •
name— Name of Jenkins job,str- •
config_xml— New XML configuration,strJenkins.build_job_url(name, parameters=None, token=None)- Get URL to trigger build job.
Parameters- •
parameters— parameters for job, or None.,dict- •
token— (optional) token for building job,strReturns- URL for building job
Jenkins.build_job(name, parameters=None, token=None)- Trigger build job.
Parameters- •
name— name of job- •
parameters— parameters for job, orNone,dict- •
token— Jenkins API tokenJenkins.run_script(script)- Execute a groovy script on the jenkins master.
Parametersscript— The groovy script,stringReturns- The result of the script run.
Example::>>> j = Jenkins() >>> info = j.run_script("println(Jenkins.instance.pluginManager.plugins)") >>> 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]'Jenkins.stop_build(name, number)- Stop a running Jenkins build.
Parameters- •
name— Name of Jenkins job,str- •
number— Jenkins build number for the job,intJenkins.get_nodes()- Get a list of nodes connected to the Master
Returns- List of nodes,
[ { str: str, str: bool} ] Jenkins.get_node_info(name, depth=0)- Get node information dictionary
Parameters- •
name— Node name,str- •
depth— JSON depth,intReturns- Dictionary of node info,
dict Jenkins.node_exists(name)- Check whether a node exists
Parametersname— Name of Jenkins node,strReturnsTrueif Jenkins node existsJenkins.assert_node_exists(name, exception_message=’node[%s] does not exist’)- Raise an exception if a node does not exist
Parameters- •
name— Name of Jenkins node,str- •
exception_message— Message to use for the exception. Formatted withnameThrowsJenkinsExceptionwhenever the node does not existJenkins.delete_node(name)- Delete Jenkins node permanently.
Parametersname— Name of Jenkins node,strJenkins.disable_node(name, msg=”)- Disable a node
Parameters- •
name— Jenkins node name,str- •
msg— Offline message,strJenkins.enable_node(name)- Enable a node
Parametersname— Jenkins node name,strJenkins.create_node(name, numExecutors=2, nodeDescription=None, remoteFS=’/var/lib/jenkins’, labels=None, exclusive=False, launcher=’hudson.slaves.CommandLauncher’, launcher_params={})- Create a node
Parameters- •
name— name of node to create,str- •
numExecutors— number of executors for node,int- •
nodeDescription— Description of node,str- •
remoteFS— Remote filesystem location to use,str- •
labels— Labels to associate with node,str- •
exclusive— Use this node for tied jobs only,bool- •
launcher— The launch method for the slave,jenkins.LAUNCHER_COMMAND,jenkins.LAUNCHER_SSH,jenkins.LAUNCHER_JNLP,jenkins.LAUNCHER_WINDOWS_SERVICE- •
launcher_params— Additional parameters for the launcher,dictJenkins.get_node_config(name)- Get the configuration for a node.
Parametersname— Jenkins node name,strJenkins.reconfig_node(name, config_xml)- Change the configuration for an existing node.
Parameters- •
name— Jenkins node name,str- •
config_xml— New XML configuration,strJenkins.get_build_console_output(name, number)- Get build console text.
Parameters- •
name— Job name,str- •
name— Build number,intReturns- Build console output,
str Jenkins.get_view_name(name)- Return the name of a view using the API.
Parametersname— View name,strReturns- Name of view or None
Jenkins.assert_view_exists(name, exception_message=’view[%s] does not exist’)- Raise an exception if a view does not exist
Parameters- •
name— Name of Jenkins view,str- •
exception_message— Message to use for the exception. Formatted withnameThrowsJenkinsExceptionwhenever the view does not existJenkins.view_exists(name)- Check whether a view exists
Parametersname— Name of Jenkins view,strReturnsTrueif Jenkins view existsJenkins.get_views()- Get list of views running.
Returns- list of views,
[ { str: str} ] Jenkins.delete_view(name)- Delete Jenkins view permanently.
Parametersname— Name of Jenkins view,strJenkins.create_view(name, config_xml)- Create a new Jenkins view
Parameters- •
name— Name of Jenkins view,str- •
config_xml— config file text,strJenkins.reconfig_view(name, config_xml)- Change configuration of existing Jenkins view.
Parameters- •
name— Name of Jenkins view,str- •
config_xml— New XML configuration,strJenkins.get_view_config(name)- Get configuration of existing Jenkins view.
Parametersname— Name of Jenkins view,strReturns- view configuration (XML format)
Returns the ‘Authentication’ header value.
All methods will raise JenkinsException on failure.
That is roughly an identity method which can be used to quickly verify a job exist or is accessible without causing too much stress on the server side.
This should only be used to extends the Jenkins API.
Example:
>>> j = Jenkins() >>> next_build_number = j.get_job_info('build_name')['nextBuildNumber'] >>> output = j.build_job('build_name') >>> from time import sleep;
sleep(10) >>> build_info = j.get_build_info('build_name', next_build_number) >>> print(build_info)
{
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'
}
This information includes job list and view information.
Example:
>>> j = Jenkins() >>> info = j.get_info() >>> jobs = info[‘jobs’] >>> print(jobs[0])
{
u’url’ : u’http://your_url_here/job/my_job/’, u’color’ : u’blue’, u’name’ : u’my_job’
}
Example:
>>> j = Jenkins() >>> info = j.get_version() >>> print info >>> 1.541
This method retrieves information about each plugin that is installed on master.
Example:
>>> j = Jenkins() >>> info = j.get_plugins_info() >>> print(info)
[{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}, ..]
This method retrieves information about a speicifc plugin. The passed in plugin name (short or long) must be an exact match.
Example:
>>> j = Jenkins() >>> info = j.get_plugin_info(“Gearman Plugin”) >>> print(info)
{
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
}
Each job is a dictionary with ‘name’, ‘url’, and ‘color’ keys.
To re-enable, call Jenkins.enable_job().
To create a new job, see Jenkins.create_job().
Authenticated setups may require configuring a token on the server side.
Each node is a dict with keys ‘name’ and ‘offline’
That is roughly an identity method which can be used to quickly verify a view exists or is accessible without causing too much stress on the server side.
Each view is a dictionary with ‘name’ and ‘url’ keys.
To create a new view, see Jenkins.create_view().
EXAMPLE USAGE
Example usage:
import jenkins j = jenkins.Jenkins('http://your_url_here', 'username', 'password') j.get_jobs() j.create_job('empty', jenkins.EMPTY_CONFIG_XML) j.disable_job('empty') j.copy_job('empty', 'empty_copy') j.enable_job('empty_copy') j.reconfig_job('empty_copy', jenkins.RECONFIG_XML) j.delete_job('empty') j.delete_job('empty_copy') j.get_views() j.create_view('EMPTY', jenkins.EMPTY_VIEW_CONFIG_XML) j.view_exists('EMPTY') j.delete_view('EMPTY')
#build a parameterized job
#requires setting up api - test job to accept 'param1' & 'param2'
j.build_job('api-test', {'param1' : 'test value 1', 'param2' : 'test value 2' }) last_build_number = j.get_job_info('api-test')['lastCompletedBuild']['number'] build_info = j.get_job_info('api-test', last_build_number) print(build_info)
Look at the api for more details.
INSTALLING
The module is known to pip and Debian-based distributions as python-jenkins.
pip:
pip install python-jenkins
easy_install:
easy_install python-jenkins
The module has been packaged since Ubuntu Oneiric (11.10):
apt-get install python-jenkins
And on Fedora 19 and later:
yum install python-jenkins
For development:
python setup.py develop
Documentation
Documentation is included in the doc folder. To generate docs locally execute the command:
tox -e docs
The generated documentation is then available under doc/build/html/index.html.
Unit Tests
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
- •
- Note: View
tox.inito run tests on other versions of Python.
Test Coverage
To measure test coverage, execute the command:
tox -e cover
- •
- genindex
- •
- modindex
- •
- search
AUTHOR
Ken Conley, James Page, Tully Foote, Matthew Gertner
COPYRIGHT
2010, Willow Garage