JenkinsAPI
JenkinsAPI is a Python library that provides an object-oriented interface for interacting with a Jenkins continuous integration server. It wraps the Jenkins REST API, making it easier to query the server's state, manage jobs, builds, nodes, and artifacts, and automate various Jenkins tasks. The library is actively maintained, with regular updates addressing bug fixes and new features, and is currently at version 0.3.22.
Warnings
- breaking Jenkins versions 1.518 and above require disabling 'Prevent Cross Site Request Forgery exploits' in Jenkins' global security configuration for `jenkinsapi` to function correctly without additional configuration for CSRF tokens.
- gotcha The 'Jenkins Location' in Jenkins' global settings must be correctly configured, otherwise the REST API (which `jenkinsapi` uses) may not work as expected.
- gotcha For Jenkins versions 1.426 and above, it is strongly recommended to use a Jenkins API token for authentication instead of a user's literal password. Using passwords directly is less secure.
- gotcha When connecting to a Jenkins instance with a very large number of jobs, `jenkinsapi` might attempt to eagerly load information for all jobs, which can lead to long delays or timeouts. This behavior may cause scripts to hang or run out of memory.
- gotcha Reliably tracking build queue items and their execution status can be challenging on highly active Jenkins servers. Queue items might be deleted between API calls, potentially leading to incorrect build status mappings or missed build events.
Install
-
pip install jenkinsapi
Imports
- Jenkins
from jenkinsapi.jenkins import Jenkins
Quickstart
import os
from jenkinsapi.jenkins import Jenkins
JENKINS_URL = os.environ.get('JENKINS_URL', 'http://localhost:8080')
JENKINS_USERNAME = os.environ.get('JENKINS_USERNAME', 'admin') # Or 'JENKINS_USER'
JENKINS_API_TOKEN = os.environ.get('JENKINS_API_TOKEN', 'your_api_token_here') # Use an API token, not a user's password
def connect_to_jenkins():
try:
# It's highly recommended to use an API token for authentication,
# which can be generated from your Jenkins user configuration page.
server = Jenkins(JENKINS_URL, username=JENKINS_USERNAME, password=JENKINS_API_TOKEN)
print(f"Successfully connected to Jenkins at {JENKINS_URL}. Jenkins version: {server.version}")
# Example: Get the number of jobs
print(f"Number of jobs configured: {len(server.jobs)}")
# Example: List names of first 5 jobs
# print("First 5 job names:")
# for i, job_name in enumerate(server.jobs.keys()):
# if i >= 5:
# break
# print(f" - {job_name}")
except Exception as e:
print(f"Failed to connect to Jenkins or retrieve information: {e}")
print("Ensure JENKINS_URL, JENKINS_USERNAME, and JENKINS_API_TOKEN environment variables are set correctly.")
if __name__ == '__main__':
connect_to_jenkins()