in this tutorial, I’ll learn How to access Jenkins API using python. Jenkins is providing an API interface to access all resources. We will use python-jenkins, It’s a third-party API package to access Jenkins rest API.
There are two Python packages you can use for this task:
- The Python Jenkins package
- JenkinsAPI
What is Jenkins
Jenkins is a very popular self-contained and open-source build tool. You can use Jenkins for building, testing, and deploying software into the server. You can get Jenkins API information from the bottom of Jenkins server. The Jenkins provides hundreds of plugins to support building, deploying and automating any project. You can get more information from here.
Jenkins API Python
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.
You can use it for following jenkins operations –
- 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 folders
- Set the next build number
- Install plugins
- and many more..
We ll create test.py
file and add all code to access Jenkins resources using python API.
Install Python Package
Let’s install python-jenkins
into your python application. You can use pip for that:
pip install python-jenkins
Create Jenkins Client
Now, we’ll create a Jenkins client using API credentials, that ll use further to access the rest API:
import jenkins jenkins_client = jenkins.Jenkins('https://jenkins-hostname:port/', username='user',<br>password='password')
The above client is returned are usually a Python dictionary.
Where is :
https://jenkins-hostname
: This is the Hostname of jenkins server.port
: This is the port number of jenkins server.user
: The jenkins server api username.password
: This is jenkins server api password.
How To Get All Jenkins Jobs
You can access all configured jenkins job using python package inbuilt method.The below code use to getting all the jobs that are configured on your CI system:
import jenkins jenkins_client = jenkins.Jenkins('https://jenkins-hostname:port/', username='user',password='password') # Get all builds jobs = jenkins_client.get_jobs() print(jobs)
The above code’ll access all configured Jenkins jobs and loop through all the jobs, We’ll print out their job names.
You can also checkout other python API tutorials: