Operations 9 min read

Managing Jenkins Jobs with the python‑jenkins API

This guide demonstrates how to use the python‑jenkins library to interact with Jenkins via its API, covering installation, configuration, job creation, copying, deletion, node management, plugin handling, and scripting examples for automating CI/CD pipelines.

DevOps Cloud Academy
DevOps Cloud Academy
DevOps Cloud Academy
Managing Jenkins Jobs with the python‑jenkins API

This article introduces the python-jenkins library as a way to control a Jenkins server programmatically from Python.

Key capabilities include creating, copying, deleting, and updating jobs; managing builds, nodes, views, credentials, plugins, and Jenkins shutdown mode; as well as retrieving detailed information such as job configurations, build data, and server version.

Usage approach : locate the desired API method in the documentation, examine its parameters, and test the call in an interactive Python interpreter.

Install the library: pip install python-jenkins==1.6.0 Example interactive session:

>>> import jenkins
>>> server = jenkins.Jenkins("http://127.0.0.1:8080", username="admin", password="admin")
>>> server.get_whoami()
{'_class': 'hudson.model.User', 'absoluteUrl': 'http://127.0.0.1:8080/user/admin', 'description': '', 'fullName': 'admin', 'id': 'admin', ...}

List all available methods on the server object:

>>> dir(server)
['_class', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_add_missing_builds', '_auth_resolved', ... 'create_job', 'copy_job', 'delete_job', 'disable_job', 'enable_job', 'get_job_config', 'get_job_info', 'build_job', 'stop_build', ...]

Typical workflow to duplicate a job:

Retrieve the XML configuration of an existing job.

Use create_job with a new name and the retrieved XML.

Verify creation with job_exists.

Example:

config_xml = server.get_job_config("demo-test")
server.create_job("demo-test-02", config_xml)
print(server.job_exists("demo-test-02"))  # True

Copying a job:

>>> server.copy_job("demo-test-02", "demo-test-03")
>>> server.job_exists("demo-test-03")
True

Below is a full script that creates a new project from a template, replaces a parameter value, and creates the job if it does not already exist:

import jenkins

# login
serverUrl = "http://127.0.0.1:8080"
username = "admin"
password = "admin"
server = jenkins.Jenkins(serverUrl, username, password)

defProjectName = "demo-devops-service"
newProjectName = "demo-test-service"

if not server.job_exists(newProjectName):
    print("Project does not exist, creating it")
    config_xml = server.get_job_config(defProjectName)
    newconfig_xml = config_xml.replace("<defaultValue>svn</defaultValue>", "<defaultValue>git</defaultValue>")
    print(newconfig_xml)
    server.create_job(newProjectName, newconfig_xml)
else:
    print("Project already exists!")

Running the script produces output similar to:

Project does not exist, creating it
<?xml version='1.1' encoding='UTF-8'?>
<project>
  <actions/>
  <description/>
  <keepDependencies>false</keepDependencies>
  <properties>
    <hudson.model.ParametersDefinitionProperty>
      <parameterDefinitions>
        <hudson.model.StringParameterDefinition>
          <name>srcType</name>
          <description/>
          <defaultValue>git</defaultValue>
          <trim>false</trim>
        </hudson.model.StringParameterDefinition>
      </parameterDefinitions>
    </hudson.model.ParametersDefinitionProperty>
  </properties>
  <scm class="hudson.scm.NullSCM"/>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders/>
  <publishers/>
  <buildWrappers/>
</project>

The resulting Jenkins UI shows the newly created job with the updated parameter, confirming that the API calls succeeded.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythonci/cdautomationDevOpsAPIJenkins
DevOps Cloud Academy
Written by

DevOps Cloud Academy

Exploring industry DevOps practices and technical expertise.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.