jenkinsapi package

Subpackages

Submodules

jenkinsapi.api module

This module is a collection of helpful, high-level functions for automating common tasks. Many of these functions were designed to be exposed to the command-line, hence they have simple string arguments.

jenkinsapi.api.block_until_complete(jenkinsurl: str, jobs: List[str], maxwait: int = 12000, interval: int = 30, raise_on_timeout: bool = True, username: str = '', password: str = '', ssl_verify: bool = True) None[source]

Wait until all of the jobs in the list are complete.

jenkinsapi.api.get_artifacts(jenkinsurl: str, jobname: str, build_no: int, username: str = '', password: str = '', ssl_verify: bool = True)[source]

Find all the artifacts for the latest build of a job.

jenkinsapi.api.get_build(jenkinsurl: str, jobname: str, build_no: int, username: str = '', password: str = '', ssl_verify: bool = True) Build[source]

A convenience function to fetch down the test results from a jenkins job by build number.

jenkinsapi.api.get_latest_build(jenkinsurl: str, jobname: str, username: str = '', password: str = '', ssl_verify: bool = True) Build[source]

A convenience function to fetch down the very latest test results from a jenkins job.

jenkinsapi.api.get_latest_complete_build(jenkinsurl: str, jobname: str, username: str = '', password: str = '', ssl_verify: bool = True) Build[source]

A convenience function to fetch down the very latest test results from a jenkins job.

jenkinsapi.api.get_latest_test_results(jenkinsurl: str, jobname: str, username: str = '', password: str = '', ssl_verify: bool = True) ResultSet[source]

A convenience function to fetch down the very latest test results from a jenkins job.

jenkinsapi.api.get_nested_view_from_url(url: str, username: str = '', password: str = '', ssl_verify: bool = True) View[source]

Returns View based on provided URL. Convenient for nested views.

jenkinsapi.api.get_view_from_url(url: str, username: str = '', password: str = '', ssl_verify: bool = True) View[source]

Factory method

jenkinsapi.api.grab_artifact(jenkinsurl: str, jobname: str, artifactid, targetdir: str, username: str = '', password: str = '', strict_validation: bool = True, ssl_verify: bool = True) None[source]

Convenience method to find the latest good version of an artifact and save it to a target directory. Directory is made automatically if not exists.

jenkinsapi.api.install_artifacts(artifacts, dirstruct: Dict[str, str], installdir: str, basestaticurl: str, strict_validation: bool = False)[source]

Install the artifacts.

jenkinsapi.api.search_artifact_by_regexp(jenkinsurl: str, jobname: str, artifactRegExp: Pattern, username: str = '', password: str = '', ssl_verify: bool = True) Artifact[source]

Search the entire history of a Jenkins job for a build which has an artifact whose name matches a supplied regular expression. Return only that artifact.

@param jenkinsurl: The base URL of the jenkins server @param jobid: The name of the job we are to search through @param artifactRegExp: A compiled regular expression object

(not a re-string)

@param username: Jenkins login user name, optional @param password: Jenkins login password, optional

jenkinsapi.api.search_artifacts(jenkinsurl: str, jobname: str, artifact_ids=None, username: str = '', password: str = '', ssl_verify: bool = True)[source]

Search the entire history of a jenkins job for a list of artifact names. If same_build is true then ensure that all artifacts come from the same build of the job

jenkinsapi.artifact module

Artifacts can be used to represent data created as a side-effect of running a Jenkins build.

Artifacts are files which are associated with a single build. A build can have any number of artifacts associated with it.

This module provides a class called Artifact which allows you to download objects from the server and also access them as a stream.

class jenkinsapi.artifact.Artifact(filename: str, url: str, build: Build, relative_path: str | None = None)[source]

Bases: object

Represents a single Jenkins artifact, usually some kind of file generated as a by-product of executing a Jenkins build.

get_data() Any[source]

Grab the text of the artifact

get_jenkins_obj() Jenkins[source]
save(fspath: str, strict_validation: bool = False) str[source]

Save the artifact to an explicit path. The containing directory must exist. Returns a reference to the file which has just been writen to.

Parameters:

fspath – full pathname including the filename, str

Returns:

filepath

save_to_dir(dirpath: str, strict_validation: bool = False) str[source]

Save the artifact to a folder. The containing directory must exist, but use the artifact’s default filename.

jenkinsapi.build module

A Jenkins build represents a single execution of a Jenkins Job.

Builds can be thought of as the second level of the Jenkins hierarchy beneath Jobs. Builds can have state, such as whether they are running or not. They can also have outcomes, such as whether they passed or failed.

Build objects can be associated with Results and Artifacts.

class jenkinsapi.build.Build(url: str, buildno: int, job: Job, depth: int = 1)[source]

Bases: JenkinsBase

Represents a Jenkins build, executed in context of a job.

STR_TOTALCOUNT = 'totalCount'
STR_TPL_NOTESTS_ERR = '%s has status %s, and does not have any test results'
block() None[source]
block_until_complete(delay: int = 15) None[source]
get_actions() Dict[str, Any][source]
get_artifact_dict() dict[str, Artifact][source]
get_artifacts() Iterator[Artifact][source]
get_build_url() str[source]
get_causes() List[str][source]

Returns a list of causes. There can be multiple causes lists and some of the can be empty. For instance, when a build is manually aborted, Jenkins could add an empty causes list to the actions dict. Empty ones are ignored.

get_changeset_items()[source]

Returns a list of changeSet items.

Each item has structure as in following example: {

“affectedPaths”: [

“content/rcm/v00-rcm-xccdf.xml”

], “author” : {

“absoluteUrl”: “http://jenkins_url/user/username79”, “fullName”: “username”

}, “commitId”: “3097”, “timestamp”: 1414398423091, “date”: “2014-10-27T08:27:03.091288Z”, “msg”: “commit message”, “paths”: [{

“editType”: “edit”, “file”: “/some/path/of/changed_file”

}], “revision”: 3097, “user”: “username”

}

get_console() str[source]

Return the current state of the text console.

get_description() str[source]
get_downstream_builds() List[Build][source]

Get the downstream builds for this build :return List of Build or None

get_downstream_job_names() List[str][source]

Get the downstream job names for this build :return List of string or None

get_downstream_jobs() List[Job][source]

Get the downstream jobs for this build :return List of jobs or None

get_duration() timedelta[source]
get_env_vars() Dict[str, str][source]

Return the environment variables.

This method is using the Environment Injector plugin: https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin

get_estimated_duration() int | None[source]

Return the estimated build duration (in seconds) or none.

get_jenkins_obj() Jenkins[source]
get_master_build() 'Build' | None[source]

Get the master build if it exist, None otherwise :return Build or None

get_master_build_number() int | None[source]

Get the master build number if it exist, None otherwise :return: int or None

get_master_job() Job | None[source]

Get the master job object if it exist, None otherwise :return: Job or None

get_master_job_name() str | None[source]

Get the master job name if it exist, None otherwise :return: String or None

get_matrix_runs() Iterator[Build][source]

For a matrix job, get the individual builds for each matrix configuration :return: Generator of Build

get_number() int[source]
get_params() dict[str, str][source]

Return a dictionary of params names and their values, or an empty dictionary if no parameters are returned.

get_repo_url() str[source]
get_result_url() str[source]

Return the URL for the object which provides the job’s result summary.

get_resultset() ResultSet[source]

Obtain detailed results for this build.

Raises NoResults if the build has no results.

Returns:

ResultSet

get_revision() str[source]
get_revision_branch() str[source]
get_slave() str[source]
get_status() str[source]
get_timestamp() datetime[source]

Returns build timestamp in UTC

get_upstream_build() 'Build' | None[source]

Get the upstream build if it exist, None otherwise :return Build or None

get_upstream_build_number() int | None[source]

Get the upstream build number if it exist, None otherwise :return: int or None

get_upstream_job() Job | None[source]

Get the upstream job object if it exist, None otherwise :return: Job or None

get_upstream_job_name() str | None[source]

Get the upstream job name if it exist, None otherwise :return: String or None

has_resultset() bool[source]

Return a boolean, true if a result set is available. false if not.

is_good() bool[source]

Return a bool, true if the build was good. If the build is still running, return False.

is_kept_forever() bool[source]
is_running() bool[source]

Return a bool if running.

property name
stop() bool[source]

Stops the build execution if it’s running :return: boolean True if succeeded False otherwis

stream_logs(interval=0) Iterator[str][source]

Return generator which streams parts of text console.

toggle_keep() None[source]

Toggle “keep this build forever” on and off

jenkinsapi.config module

Jenkins configuration

jenkinsapi.constants module

Constants for jenkinsapi

jenkinsapi.credential module

Module for jenkinsapi Credential class

class jenkinsapi.credential.AmazonWebServicesCredentials(cred_dict)[source]

Bases: Credential

AWS credential using the CloudBees AWS Credentials Plugin See https://wiki.jenkins.io/display/JENKINS/CloudBees+AWS+Credentials+Plugin

Constructor expects following dict:
{

‘credential_id’: str, Automatically set by jenkinsapi ‘displayName’: str, Automatically set by Jenkins ‘fullName’: str, Automatically set by Jenkins ‘description’: str, ‘accessKey’: str, ‘secretKey’: str, ‘iamRoleArn’: str, ‘iamMfaSerialNumber’: str

}

When creating credential via jenkinsapi automatic fields not need to be in dict

get_attributes()[source]

Used by Credentials object to create credential in Jenkins

get_attributes_xml()[source]

Used by Credentials object to update a credential in Jenkins

class jenkinsapi.credential.Credential(cred_dict, jenkins_class='')[source]

Bases: object

Base abstract class for credentials

Credentials returned from Jenkins don’t hold any sensitive information, so there is nothing useful can be done with existing credentials besides attaching them to Nodes or other objects.

You can create concrete Credential instance: UsernamePasswordCredential or SSHKeyCredential by passing credential’s description and credential dict.

Each class expects specific credential dict, see below.

get_attributes()[source]
get_attributes_xml()[source]
class jenkinsapi.credential.SSHKeyCredential(cred_dict: dict)[source]

Bases: Credential

SSH key credential

Constructr expects following dict:
{

‘credential_id’: str, Automatically set by jenkinsapi ‘displayName’: str, Automatically set by Jenkins ‘fullName’: str, Automatically set by Jenkins ‘typeName’: str, Automatically set by Jenkins ‘description’: str, ‘userName’: str, ‘passphrase’: str, SSH key passphrase, ‘private_key’: str Private SSH key

}

private_key value is parsed to find type of credential to create:

private_key starts with - the value is private key itself

These credential variations are no longer supported by SSH Credentials plugin. jenkinsapi will raise ValueError if they are used:

private_key starts with / the value is a path to key private_key starts with ~ the value is a key from ~/.ssh

When creating credential via jenkinsapi automatic fields not need to be in dict

property attrs
get_attributes()[source]

Used by Credentials object to create credential in Jenkins

get_attributes_xml()[source]

Used by Credentials object to update a credential in Jenkins

class jenkinsapi.credential.SecretTextCredential(cred_dict)[source]

Bases: Credential

Secret text credential

Constructor expects following dict:
{

‘credential_id’: str, Automatically set by jenkinsapi ‘displayName’: str, Automatically set by Jenkins ‘fullName’: str, Automatically set by Jenkins ‘typeName’: str, Automatically set by Jenkins ‘description’: str, ‘secret’: str,

}

When creating credential via jenkinsapi automatic fields not need to be in dict

get_attributes()[source]

Used by Credentials object to create credential in Jenkins

get_attributes_xml()[source]

Used by Credentials object to update a credential in Jenkins

class jenkinsapi.credential.UsernamePasswordCredential(cred_dict: dict)[source]

Bases: Credential

Username and password credential

Constructor expects following dict:
{

‘credential_id’: str, Automatically set by jenkinsapi ‘displayName’: str, Automatically set by Jenkins ‘fullName’: str, Automatically set by Jenkins ‘typeName’: str, Automatically set by Jenkins ‘description’: str, ‘userName’: str, ‘password’: str

}

When creating credential via jenkinsapi automatic fields not need to be in dict

get_attributes()[source]

Used by Credentials object to create credential in Jenkins

get_attributes_xml()[source]

Used by Credentials object to update a credential in Jenkins

jenkinsapi.credentials module

This module implements the Credentials class, which is intended to be a container-like interface for all of the Global credentials defined on a single Jenkins node.

class jenkinsapi.credentials.Credentials(baseurl: str, jenkins_obj: Jenkins)[source]

Bases: JenkinsBase

This class provides a container-like API which gives access to all global credentials on a Jenkins node.

Returns a list of Credential Objects.

get(item, default)[source]
get_jenkins_obj() Jenkins[source]
iteritems() Iterator[str, 'Credential'][source]
iterkeys()[source]
keys()[source]
class jenkinsapi.credentials.Credentials2x(baseurl: str, jenkins_obj: Jenkins)[source]

Bases: Credentials

This class provides a container-like API which gives access to all global credentials on a Jenkins node.

Returns a list of Credential Objects.

class jenkinsapi.credentials.CredentialsById(baseurl: str, jenkins_obj: Jenkins)[source]

Bases: Credentials2x

This class provides a container-like API which gives access to all global credentials on a Jenkins node.

Returns a list of Credential Objects.

iteritems()[source]

jenkinsapi.custom_exceptions module

Module for custom_exceptions.

Where possible we try to throw exceptions with non-generic, meaningful names.

exception jenkinsapi.custom_exceptions.AlreadyExists[source]

Bases: JenkinsAPIException

Method requires POST and not GET

exception jenkinsapi.custom_exceptions.ArtifactBroken[source]

Bases: JenkinsAPIException

An artifact is broken, wrong

exception jenkinsapi.custom_exceptions.ArtifactsMissing[source]

Bases: NotFound

Cannot find a build with all of the required artifacts.

exception jenkinsapi.custom_exceptions.BadParams[source]

Bases: JenkinsAPIException

Invocation was given bad or inappropriate params

exception jenkinsapi.custom_exceptions.BadURL[source]

Bases: ValueError, JenkinsAPIException

A URL appears to be broken

exception jenkinsapi.custom_exceptions.FailedNoResults[source]

Bases: NoResults

A build did not publish any results because it failed

exception jenkinsapi.custom_exceptions.JenkinsAPIException[source]

Bases: Exception

Base class for all errors

exception jenkinsapi.custom_exceptions.NoBuildData[source]

Bases: NotFound

A job has no build data.

exception jenkinsapi.custom_exceptions.NoResults[source]

Bases: JenkinsAPIException

A build did not publish any results.

exception jenkinsapi.custom_exceptions.NotAuthorized[source]

Bases: JenkinsAPIException

Not Authorized to access resource

exception jenkinsapi.custom_exceptions.NotBuiltYet[source]

Bases: NotFound

A job has no build data.

exception jenkinsapi.custom_exceptions.NotConfiguredSCM[source]

Bases: JenkinsAPIException

It’s a job that doesn’t have configured SCM

exception jenkinsapi.custom_exceptions.NotFound[source]

Bases: JenkinsAPIException

Resource cannot be found

exception jenkinsapi.custom_exceptions.NotInQueue[source]

Bases: JenkinsAPIException

It’s a job that is not in the queue

exception jenkinsapi.custom_exceptions.NotSupportSCM[source]

Bases: JenkinsAPIException

It’s a SCM that does not supported by current version of jenkinsapi

exception jenkinsapi.custom_exceptions.PostRequired[source]

Bases: JenkinsAPIException

Method requires POST and not GET

exception jenkinsapi.custom_exceptions.TimeOut[source]

Bases: JenkinsAPIException

Some jobs have taken too long to complete.

exception jenkinsapi.custom_exceptions.UnknownJob[source]

Bases: KeyError, NotFound

Jenkins does not recognize the job requested.

exception jenkinsapi.custom_exceptions.UnknownNode[source]

Bases: KeyError, NotFound

Jenkins does not recognize the node requested.

exception jenkinsapi.custom_exceptions.UnknownPlugin[source]

Bases: KeyError, NotFound

Jenkins does not recognize the plugin requested.

exception jenkinsapi.custom_exceptions.UnknownQueueItem[source]

Bases: KeyError, NotFound

Jenkins does not recognize the requested queue item

exception jenkinsapi.custom_exceptions.UnknownView[source]

Bases: KeyError, NotFound

Jenkins does not recognize the view requested.

jenkinsapi.executor module

Module for jenkinsapi Executer class

class jenkinsapi.executor.Executor(baseurl: str, nodename: str, jenkins_obj: Jenkins, number: int)[source]

Bases: JenkinsBase

Class to hold information on nodes that are attached as slaves to the master jenkins instance

get_current_executable() str[source]

Returns the current Queue.Task this executor is running.

get_jenkins_obj() Jenkins[source]
get_number() int[source]

Get Executor number.

get_progress() str[source]

Returns percentage

is_idle() bool[source]

Returns Boolean: whether Executor is idle or not.

likely_stuck() bool[source]

Returns Boolean: whether Executor is likely stuck or not.

jenkinsapi.executors module

This module implements the Executors class, which is intended to be a container-like interface for all of the executors defined on a single Jenkins node.

class jenkinsapi.executors.Executors(baseurl: str, nodename: str, jenkins: Jenkins)[source]

Bases: JenkinsBase

This class provides a container-like API which gives access to all executors on a Jenkins node.

Returns a list of Executor Objects.

get_jenkins_obj() Jenkins[source]

jenkinsapi.fingerprint module

Module for jenkinsapi Fingerprint

class jenkinsapi.fingerprint.Fingerprint(baseurl: str, id_: str, jenkins_obj: Jenkins)[source]

Bases: JenkinsBase

Represents a jenkins fingerprint on a single artifact file ??

RE_MD5 = re.compile('^([0-9a-z]{32})$')
get_info()[source]

Returns a tuple of build-name, build# and artifact filename for a good build.

get_jenkins_obj() Jenkins[source]
valid() bool[source]

Return True / False if valid. If returns True, self.unknown is set to either True or False, and can be checked if we have positive validity (fingerprint known at server) or negative validity (fingerprint not known at server, but not really an error).

validate() bool[source]
validate_for_build(filename: str, job: str, build: int) bool[source]

jenkinsapi.jenkins module

Module for jenkinsapi Jenkins object

class jenkinsapi.jenkins.Jenkins(baseurl: str, username: str = '', password: str = '', requester=None, lazy: bool = False, ssl_verify: bool = True, cert=None, timeout: int = 10, use_crumb: bool = True, max_retries=None)[source]

Bases: JenkinsBase

Represents a jenkins environment.

base_server_url()[source]
build_job(jobname: str, params=None) None[source]

Invoke a build by job name :param jobname: name of exist job, str :param params: the job params, dict :return: none

cancel_quiet_down()[source]

Cancel the effect of the quiet-down command

copy_job(jobname: str, newjobname: str) Job[source]
create_job(jobname: str, xml) Job[source]

Create a job

alternatively you can create job using Jobs object: self.jobs[‘job_name’] = config :param jobname: name of new job, str :param config: configuration of new job, xml :return: new Job obj

create_multibranch_pipeline_job(jobname, xml, block=True, delay=60)[source]
Returns:

list of new Job objects

create_node(name: str, num_executors: int = 2, node_description: str = '', remote_fs: str = '/var/lib/jenkins', labels=None, exclusive: bool = False) Node[source]

Create a new JNLP slave node by name.

To create SSH node, please see description in Node class

Parameters:
  • name – fqdn of slave, str

  • num_executors – number of executors, int

  • node_description – a freetext field describing the node

  • remote_fs – jenkins path, str

  • labels – labels to associate with slave, str

  • exclusive – tied to specific job, boolean

Returns:

node obj

create_node_with_config(name: str, config) Node | None[source]

Create a new slave node with specific configuration. Config should be resemble the output of node.get_node_attributes() :param str name: name of slave :param dict config: Node attributes for Jenkins API request

to create node (See function output Node.get_node_attributes())

Returns:

node obj

property credentials
property credentials_by_id
delete_job(jobname: str) None[source]

Delete a job by name :param jobname: name of a exist job, str :return: new jenkins_obj

delete_node(nodename: str) None[source]

Remove a node from the managed slave list Please note that you cannot remove the master node

Parameters:

nodename – string holding a hostname

Returns:

None

delete_plugin(plugin: str | Plugin, restart: bool = True, force_restart: bool = False, wait_for_reboot: bool = True, no_reboot_warning: bool = False) None[source]

Delete a plugin and optionally restart jenkins. Will not delete dependencies. @param plugin: Plugin (string or Plugin object) to be deleted @param restart: Boolean, restart Jenkins when required by plugin @param force_restart: Boolean, force Jenkins to restart,

ignoring plugin preferences

delete_plugins(plugin_list, restart: bool = True, force_restart: bool = False, wait_for_reboot: bool = True, no_reboot_warning: bool = False)[source]

Delete a list of plugins and optionally restart jenkins. Will not delete dependencies. @param plugin_list: List of plugins (strings, Plugin objects or

a mix of the two) to be deleted

@param restart: Boolean, restart Jenkins when required by plugin @param force_restart: Boolean, force Jenkins to restart,

ignoring plugin preferences

delete_view_by_url(viewurl: str)[source]
generate_new_api_token(new_token_name: str = 'Token By jenkinsapi python')[source]
get_artifact_data(id_)[source]
get_create_url() str[source]
get_credentials(cred_class=<class 'jenkinsapi.credentials.Credentials2x'>)[source]

Return credentials

get_executors(nodename: str) Executors[source]
get_jenkins_obj()[source]
get_jenkins_obj_from_url(url: str)[source]
get_job(jobname: str) Job[source]

Get a job by name :param jobname: name of the job, str :return: Job obj

get_job_by_url(url: str, job_name: str) Job[source]

Get a job by url :param url: jobs’ url :param jobname: name of the job, str :return: Job obj

get_jobs()[source]

Fetch all the build-names on this Jenkins server.

get_jobs_info()[source]

Get the jobs information :return url, name

get_jobs_list()[source]
get_label(label_name: str) Label[source]
get_master_data()[source]
get_node(nodename: str) Node[source]

Get a node object for a specific node

get_node_url(nodename: str = '') str[source]

Return the url for nodes

get_nodes() Nodes[source]
get_nodes_url() str[source]
get_plugins(depth: int = 1) Plugins[source]
get_plugins_url(depth)[source]
get_queue() Queue[source]
get_queue_url()[source]
get_view_by_url(view_url: str)[source]
has_job(jobname: str) bool[source]

Does a job by the name specified exist :param jobname: string :return: boolean

has_node(nodename: str) bool[source]

Does a node by the name specified exist :param nodename: string, hostname :return: boolean

has_plugin(plugin_name: str) bool[source]
install_plugin(plugin: str | Plugin, restart: bool = True, force_restart: bool = False, wait_for_reboot: bool = True, no_reboot_warning: bool = False)[source]

Install a plugin and optionally restart jenkins. @param plugin: Plugin (string or Plugin object) to be installed @param restart: Boolean, restart Jenkins when required by plugin @param force_restart: Boolean, force Jenkins to restart,

ignoring plugin preferences

@param no_warning: Don’t show warning when restart is needed and restart parameters are set to False

install_plugins(plugin_list, restart: bool = True, force_restart: bool = False, wait_for_reboot: bool = True, no_reboot_warning: bool = False) None[source]

Install a list of plugins and optionally restart jenkins. @param plugin_list: List of plugins (strings, Plugin objects or

a mix of the two) to be installed

@param restart: Boolean, restart Jenkins when required by plugin @param force_restart: Boolean, force Jenkins to restart,

ignoring plugin preferences

property is_quieting_down: bool
items()[source]
Parameters:

return – A list of pairs. Each pair will be (job name, Job object)

iteritems()[source]
iterkeys()[source]
property jobs
keys()[source]
property nodes
property plugins
quiet_down()[source]

Put Jenkins in a Quiet mode, preparation for restart. No new builds started

rename_job(jobname: str, newjobname: str) Job[source]

Rename a job :param jobname: name of a exist job, str :param newjobname: name of new job, str :return: new Job obj

run_groovy_script(script: str) str[source]

Runs the requested groovy script on the Jenkins server returning the result as text. Raises a JenkinsAPIException if the returned HTTP response code from the POST request is not 200 OK.

Example:

server = Jenkins(…) script = ‘println “Hello world!”’ result = server.run_groovy_script(script) print(result) # will print “Hello world!”

safe_exit(wait_for_exit: bool = True, max_wait: int = 360)[source]

Restarts jenkins when no jobs are running, except for pipeline jobs

safe_restart(wait_for_reboot: bool = True)[source]

restarts jenkins when no jobs are running

shutdown() None[source]
validate_fingerprint(id_)[source]
validate_fingerprint_for_build(digest, filename, job, build)[source]
property version: str

Return version number of Jenkins

property views

jenkinsapi.jenkinsbase module

Module for JenkinsBase class

class jenkinsapi.jenkinsbase.JenkinsBase(baseurl: str, poll: bool = True)[source]

Bases: object

This appears to be the base object that all other jenkins objects are inherited from

get_data(url, params=None, tree=None)[source]
get_jenkins_obj()[source]
poll(tree=None)[source]
pprint()[source]

Print out all the data in this object for debugging.

process_job_folder(folder, folder_path)[source]
classmethod python_api_url(url: str) str[source]
resolve_job_folders(jobs)[source]
classmethod strip_trailing_slash(url: str) str[source]

jenkinsapi.job module

Module for jenkinsapi Job

class jenkinsapi.job.Job(url: str, name: str, jenkins_obj: Jenkins)[source]

Bases: JenkinsBase, MutableJenkinsThing

Represents a jenkins job A job can hold N builds which are the actual execution environments

delete_build(build_number)[source]

Remove build

Parameters:

build_number (int) – Build number

Raises:

NotFound – When build is not found

delete_from_queue()[source]

Delete a job from the queue only if it’s enqueued :raise NotInQueue if the job is not in the queue

disable()[source]

Disable job

enable()[source]

Enable job

get_build(buildnumber)[source]
get_build_by_params(build_params, order=1)[source]
get_build_dict()[source]
get_build_ids()[source]

Return a sorted list of all good builds as ints.

get_build_metadata(buildnumber)[source]

Get the build metadata for a given build number. For large builds with tons of tests, this method is faster than get_build by returning less data.

get_build_triggerurl() str[source]
get_buildnumber_for_revision(revision, refresh=False)[source]
Parameters:
  • revision – subversion revision to look for, int

  • refresh – boolean, whether or not to refresh the revision -> buildnumber map

Returns:

list of buildnumbers, [int]

get_config()[source]

Returns the config.xml from the job

get_config_xml_url()[source]
get_description() str[source]
get_downstream_job_names()[source]

Get all the possible downstream job names :return List of String

get_downstream_jobs()[source]

Get all the possible downstream jobs :return List of Job

get_first_build()[source]
get_first_buildnumber()[source]

Get the numerical ID of the first build.

get_full_name()[source]

Get the full name for a job (including parent folders) from the job URL.

static get_full_name_from_url_and_baseurl(url, baseurl)[source]

Get the full name for a job (including parent folders) from the job URL.

get_jenkins_obj() Jenkins[source]
get_last_build()[source]

Get the last build

get_last_build_or_none()[source]

Get the last build or None if there is no builds

get_last_buildnumber()[source]

Get the numerical ID of the last build.

get_last_completed_build()[source]

Get the last build regardless of status

get_last_completed_buildnumber()[source]

Get the numerical ID of the last complete build.

get_last_failed_buildnumber()[source]

Get the numerical ID of the last failed build.

get_last_good_build()[source]

Get the last good build

get_last_good_buildnumber()[source]

Get the numerical ID of the last good build.

get_last_stable_build()[source]

Get the last stable build

get_last_stable_buildnumber()[source]

Get the numerical ID of the last stable build.

get_next_build_number()[source]

Return the next build number that Jenkins will assign.

get_params()[source]

Get the parameters for this job. Format varies by parameter type. Here is an example string parameter:

{

‘type’: ‘StringParameterDefinition’, ‘description’: ‘Parameter description’, ‘defaultParameterValue’: {‘value’: ‘default value’}, ‘name’: ‘FOO_BAR’

}

get_params_list()[source]

Gets the list of parameter names for this job.

get_queue_item()[source]

Return a QueueItem if this object is in a queue, otherwise raise an exception

get_revision_dict()[source]

Get dictionary of all revisions with a list of buildnumbers (int) that used that particular revision

get_scm_branch()[source]

Get list of SCM branches : return: list of SCM branches

get_scm_type()[source]
get_scm_url()[source]

Get list of project SCM urls For some SCM’s jenkins allow to configure and use number of SCM url’s : return: list of SCM urls

get_upstream_job_names()[source]

Get all the possible upstream job names :return List of String

get_upstream_jobs()[source]

Get all the possible upstream jobs :return List of Job

has_params()[source]

If job has parameters, returns True, else False

has_queued_build(build_params)[source]

Returns True if a build with build_params is currently queued.

invoke(securitytoken=None, block: bool = False, build_params=None, cause=None, files=None, delay: int = 5, quiet_period=None) QueueItem[source]
is_enabled()[source]
is_queued()[source]
is_queued_or_running()[source]
is_running()[source]
load_config()[source]
static mk_json_from_build_parameters(build_params, file_params=None)[source]
modify_scm_branch(new_branch, old_branch=None)[source]

Modify SCM (“Source Code Management”) branch name for configured job. :param new_branch : new repository branch name to set.

If job has multiple branches configured and “old_branch” not provided - method will allways modify first url.

Parameters:

(optional) (old_branch) – exact value of branch name to be replaced. For some SCM’s jenkins allow set multiple branches per job this parameter intended to indicate which branch need to be modified

modify_scm_url(new_source_url, old_source_url=None)[source]

Modify SCM (“Source Code Management”) url for configured job. :param new_source_url : new repository url to set.

If job has multiple repositories configured and “old_source_url” not provided - method will allways modify first url.

Parameters:

(optional) (old_source_url) – for some SCM’s jenkins allows settting multiple repositories per job this parameter intended to indicate which repository need to be modified

poll(tree=None)[source]
toggle_keep_build(build_number)[source]
update_config(config, full_response=False, encoding='utf-8')[source]

Update the config.xml to the job Also refresh the ElementTree object since the config has changed :param full_response (optional): if True, it will return the full

response object instead of just the response text. Useful for debugging and validation workflows.

jenkinsapi.jobs module

This module implements the Jobs class, which is intended to be a container-like interface for all of the jobs defined on a single Jenkins server.

class jenkinsapi.jobs.Jobs(jenkins: Jenkins)[source]

Bases: object

This class provides a container-like API which gives access to all jobs defined on the Jenkins server. It behaves like a dict in which keys are Job-names and values are actual jenkinsapi.Job objects.

build(job_name: str, params=None, **kwargs) QueueItem[source]

Executes build of a job

Parameters:
  • job_name (str) – Job name

  • params (dict) – Job parameters

  • kwargs – Parameters for Job.invoke() function

Returns QueueItem:

Object to track build progress

copy(job_name: str, new_job_name: str) Job[source]

Copy a job :param str job_name: Name of an existing job :param new_job_name: Name of new job :returns Job: new Job object

create(job_name: str, config: str | bytes) Job[source]

Create a job

Parameters:
  • jobname (str) – Name of new job

  • config (str) – XML configuration of new job

Returns Job:

new Job object

create_multibranch_pipeline(job_name: str, config: str, block: bool = True, delay: int = 60) list[Job][source]

Create a multibranch pipeline job

Parameters:
  • jobname (str) – Name of new job

  • config (str) – XML configuration of new job

  • block – block until scan is finished?

  • delay – max delay to wait for scan to finish (seconds)

:returns list of new Jobs after scan

iteritems() Iterator[str, 'Job'][source]

Iterate over the names & objects for all jobs

iterkeys() Iterator[str][source]

Iterate over the names of all available jobs

itervalues() Iterator[Job][source]

Iterate over all available jobs

keys() list[str][source]

Return a list of the names of all jobs

poll(tree='jobs[name,color,url]')[source]
rename(job_name: str, new_job_name: str) Job[source]

Rename a job

Parameters:
  • job_name (str) – Name of an existing job

  • new_job_name (str) – Name of new job

Returns Job:

new Job object

jenkinsapi.label module

Module for jenkinsapi labels

class jenkinsapi.label.Label(baseurl, labelname, jenkins_obj)[source]

Bases: JenkinsBase

Class to hold information on labels that tied to a collection of jobs

get_jenkins_obj()[source]
get_tied_job_names()[source]

Get a list of the name of tied jobs.

get_tied_jobs()[source]

Get a list of jobs.

is_online()[source]

jenkinsapi.mutable_jenkins_thing module

Module for MutableJenkinsThing

class jenkinsapi.mutable_jenkins_thing.MutableJenkinsThing[source]

Bases: object

A mixin for certain mutable objects which can be renamed and deleted.

get_delete_url() str[source]
get_rename_url() str[source]

jenkinsapi.node module

Module for jenkinsapi Node class

class jenkinsapi.node.Node(jenkins_obj: Jenkins, baseurl: str, nodename: str, node_dict, poll: bool = True)[source]

Bases: JenkinsBase

Class to hold information on nodes that are attached as slaves to the master jenkins instance

block_until_idle(timeout: int, poll_time: int = 5) None[source]

Blocks until the node become idle. :param timeout: Time in second when the wait is aborted. :param poll_time: Interval in seconds between each check. :@raise TimeOut

get_architecture() str[source]

Returns the system architecture of the node eg. “Linux (amd64)”.

get_available_physical_memory() int[source]

Returns the node’s available physical memory in bytes.

get_available_swap_space() int[source]

Returns the node’s available swap space in bytes.

get_clock_difference() int[source]

Returns the difference between the node’s clock and the master Jenkins clock. Used to detect out of sync clocks.

get_config() str[source]

Returns the config.xml from the node.

get_config_element(el_name: str) str[source]

Returns simple config element.

Better not to be used to return “nodeProperties” or “launcher”

get_jenkins_obj() Jenkins[source]
get_labels() str | None[source]

Returns the labels for a slave as a string with each label separated by the ‘ ‘ character.

get_monitor(monitor_name: str, poll_monitor=True) str[source]

Polls the node returning one of the monitors in the monitorData branch of the returned node api tree.

get_node_attributes() dict[source]

Gets node attributes as dict

Used by Nodes object when node is created

Returns:

Node attributes dict formatted for Jenkins API request to create node

get_num_executors() str[source]
get_response_time() int[source]

Returns the node’s average response time.

get_temp_path() str[source]

Returns the local path to the node’s temp directory.

get_temp_size() int[source]

Returns the size in bytes of the node’s temp directory.

get_total_physical_memory() int[source]

Returns the node’s total physical memory in bytes.

get_total_swap_space() int[source]

Returns the node’s total swap space in bytes.

get_workspace_path() str[source]

Returns the local path to the node’s Jenkins workspace directory.

get_workspace_size() int[source]

Returns the size in bytes of the node’s Jenkins workspace directory.

is_idle() bool[source]
is_jnlpagent() bool[source]
is_online() bool[source]
is_temporarily_offline() bool[source]
load_config() None[source]

Loads the config.xml for the node allowing it to be re-queried without generating new requests.

offline_reason() str[source]
set_config_element(el_name: str, value: str) None[source]

Sets simple config element

set_num_executors(value: int | str) None[source]

Sets number of executors for node

Warning! Setting number of executors on master node will erase all other settings

set_offline(message='requested from jenkinsapi') None[source]

Set node offline. If after run node state has not been changed raise AssertionError. : param message: optional string explain why you are taking this

node offline

set_online() None[source]

Set node online. Before change state verify client state: if node set ‘offline’ but ‘temporarilyOffline’ is not set - client has connection problems and AssertionError raised. If after run node state has not been changed raise AssertionError.

toggle_temporarily_offline(message='requested from jenkinsapi') None[source]

Switches state of connected node (online/offline) and set ‘temporarilyOffline’ property (True/False) Calling the same method again will bring node status back. :param message: optional string can be used to explain why you

are taking this node offline

update_offline_reason(reason: str) None[source]

Update offline reason on a temporary offline clsuter

upload_config(config_xml: str) None[source]

Uploads config_xml to the config.xml for the node.

jenkinsapi.nodes module

Module for jenkinsapi nodes

class jenkinsapi.nodes.Nodes(baseurl: str, jenkins_obj: Jenkins)[source]

Bases: JenkinsBase

Class to hold information on a collection of nodes

create_node(name: str, node_dict: dict) Node[source]

Create a new slave node

Parameters:
  • name (str) – name of slave

  • node_dict (dict) – node dict (See Node class)

Returns:

node obj

create_node_with_config(name: str, config: dict) Node | None[source]

Create a new slave node with specific configuration. Config should be resemble the output of node.get_node_attributes() :param str name: name of slave :param dict config: Node attributes for Jenkins API request

to create node (See function output Node.get_node_attributes())

Returns:

node obj

get_jenkins_obj() Jenkins[source]
items() list[tuple[str, Node]][source]

Return a copy of the container’s list of (name, node) pairs.

iteritems() Iterator[tuple[str, Node]][source]

Return an iterator over the container’s (name, node) pairs.

Using iteritems() while creating nodes may raise a RuntimeError or fail to iterate over all entries.

iterkeys() Iterator[str][source]

Return an iterator over the container’s node names.

Using iterkeys() while creating nodes may raise a RuntimeError or fail to iterate over all entries.

itervalues() Iterator[Node][source]

Return an iterator over the container’s nodes.

Using itervalues() while creating nodes may raise a RuntimeError or fail to iterate over all entries.

keys() list[str][source]

Return a copy of the container’s list of node names.

values() list[Node][source]

Return a copy of the container’s list of nodes.

jenkinsapi.plugin module

Module for jenkinsapi Plugin

class jenkinsapi.plugin.Plugin(plugin_dict: dict | str)[source]

Bases: object

Plugin class

get_attributes() str[source]

Used by Plugins object to install plugins in Jenkins

is_latest(update_center_dict: dict) bool[source]

Used by Plugins object to determine if plugin can be installed through the update center (when plugin version is latest version), or must be installed by uploading the plugin hpi file.

to_plugin(plugin_string: str) dict[source]

jenkinsapi.plugins module

jenkinsapi plugins

class jenkinsapi.plugins.Plugins(url: str, jenkins_obj: Jenkins)[source]

Bases: JenkinsBase

Plugins class for jenkinsapi

check_updates_server() None[source]
get_jenkins_obj() Jenkins[source]
get_plugins_dict() dict[str, Plugin][source]
iteritems() Generator[str, Plugin, None][source]
keys() list[str][source]
plugin_version_already_installed(plugin) bool[source]

Check if plugin version is already installed

plugin_version_is_being_installed(plugin) bool[source]

Return true if plugin is currently being installed.

property restart_required

Call after plugin installation to check if Jenkins requires a restart

property update_center_dict
property update_center_install_status

Jenkins 2.x specific

values() list[Plugin][source]

jenkinsapi.queue module

Queue module for jenkinsapi

class jenkinsapi.queue.Queue(baseurl: str, jenkins_obj: Jenkins)[source]

Bases: JenkinsBase

Class that represents the Jenkins queue

delete_item(queue_item: QueueItem)[source]
delete_item_by_id(item_id: str)[source]
get_jenkins_obj() Jenkins[source]
get_queue_item_url(item: str) str[source]
get_queue_items_for_job(job_name: str)[source]
iteritems() Iterator[Tuple[str, QueueItem]][source]
iterkeys() Iterator[str][source]
itervalues() Iterator[QueueItem][source]
keys() list[str][source]
values() list[QueueItem][source]
class jenkinsapi.queue.QueueItem(baseurl: str, jenkins_obj: Jenkins)[source]

Bases: JenkinsBase

An individual item in the queue

block_until_building(delay=5)[source]
block_until_complete(delay=5)[source]
get_build() Build[source]
get_build_number() int[source]
get_jenkins_obj() Jenkins[source]
get_job() Job[source]

Return the job associated with this queue item

get_job_name() str[source]
get_parameters()[source]

returns parameters of queue item

is_queued() bool[source]

Return True if this queued item is queued.

is_running() bool[source]

Return True if this queued item is running.

property name
property queue_id
property why

jenkinsapi.result module

Module for jenkinsapi Result

class jenkinsapi.result.Result(**kwargs)[source]

Bases: object

Result class

identifier() str[source]

Calculate an ID for this object.

jenkinsapi.result_set module

Module for jenkinsapi ResultSet

class jenkinsapi.result_set.ResultSet(url: str, build: Build)[source]

Bases: JenkinsBase

Represents a result from a completed Jenkins run.

get_jenkins_obj() Jenkins[source]
items()[source]
iteritems()[source]
keys() list[str][source]
property name

jenkinsapi.view module

Module for jenkinsapi views

class jenkinsapi.view.View(url: str, name: str, jenkins_obj: Jenkins)[source]

Bases: JenkinsBase

View class

add_job(job_name: str, job=None) bool[source]

Add job to a view

Parameters:
  • job_name – name of the job to be added

  • job – Job object to be added

Returns:

True if job has been added, False if job already exists or job not known to Jenkins

delete() None[source]

Remove this view object

get_config() str[source]

Return the config.xml from the view

get_config_xml_url() str[source]
get_jenkins_obj() Jenkins[source]
get_job_dict() dict[source]
get_job_url(str_job_name: str) str[source]
get_nested_view_dict() dict[source]
items()[source]
iteritems() Iterator[Tuple[str, Job]][source]
keys() list[str][source]
remove_job(job_name: str) bool[source]

Remove job from a view

Parameters:

job_name – name of the job to be removed

Returns:

True if job has been removed, False if job not assigned to this view

update_config(config: str) str[source]

Update the config.xml to the view

values() list[Job][source]
property views

jenkinsapi.views module

Module for jenkinsapi Views

class jenkinsapi.views.Views(jenkins)[source]

Bases: object

An abstraction on a Jenkins object’s views

CATEGORIZED_VIEW = 'org.jenkinsci.plugins.categorizedview.CategorizedJobsView'
DASHBOARD_VIEW = 'hudson.plugins.view.dashboard.Dashboard'
LIST_VIEW = 'hudson.model.ListView'
MY_VIEW = 'hudson.model.MyView'
NESTED_VIEW = 'hudson.plugins.nested_view.NestedView'
PIPELINE_VIEW = 'au.com.centrumsystems.hudson.plugin.buildpipeline.BuildPipelineView'
create(view_name, view_type='hudson.model.ListView', config=None)[source]

Create a view :param view_name: name of new view, str :param view_type: type of the view, one of the constants in Views, str :param config: XML configuration of the new view :return: new View obj or None if view was not created

iteritems()[source]

Get the names & objects for all views

iterkeys()[source]

Get the names of all available views

keys()[source]

Return a list of the names of all views

poll(tree=None)[source]

Module contents

About this library

Jenkins is the market leading continuous integration system, originally created by Kohsuke Kawaguchi. This API makes Jenkins even easier to use by providing an

easy to use conventional python interface.

Jenkins (and It’s predecessor Hudson) are fantastic projects - but they are somewhat Java-centric. Thankfully the designers have provided an excellent and complete REST interface. This library wraps up that interface as more conventional python objects in order to make most Jenkins oriented tasks simpler.

This library can help you:

  • Query the test-results of a completed build

  • Get a objects representing the latest builds of a job

  • Search for artifacts by simple criteria

  • Block until jobs are complete

  • Install artifacts to custom-specified directory structures

  • username/password auth support for jenkins instances with auth turned on

  • Ability to search for builds by subversion revision

  • Ability to add/remove/query jenkins slaves

Installing JenkinsAPI

Egg-files for this project are hosted on PyPi. Most Python users should be able to use pip or distribute to automatically install this project.

Most users can do the following:

easy_install jenkinsapi

If you’d like to install in multi-version mode:

easy_install -m jenkinsapi

Project Authors

Current code lives on github: https://github.com/salimfadhley/jenkinsapi