Jenkins and Python

There is a nice Python library that allows you to manipulate Jenkins master but having more dependencies can make it cumbersome to manage systems. For some simple things, I’m for writing my own script from scratch.

Jenkins has nice set of REST-like API interfaces. I’ve actually created an open source tool in WPF and C# around the mechanism before. I know there will be time when I will want some simple Python scripts to manipulate Jenkins jobs/builds, so I’m going to write some of it just for my reference. Hope this will help someone out there.

I have these 5 Jenkins jobs on my Jenkins instance on Azure. Let’s see if I can get the list using Python.

It may not be necessary to mention this but I’m writing the code in Python 3. It seems that they are really doing away with version 2, so… The following class lets you get the list of jobs. View code in GitHub.

import requests
import base64
import urllib3
import sys
import ssl

class jenkins_server:
    def __init__(self, base_url, username, api_token):
        self.base_url = base_url
        self.username = username
        self.api_token = api_token
        self.crumb = None

    def get_jobs(self):
        r = None
        api_url = None
        if self.base_url.endswith("/"):
            api_url = self.base_url + "api/json"
        else:
            api_url = self.base_url + "/api/json"

        try:
            urllib3.disable_warnings()
            headers = {}
            headers['Content-Type'] = 'application/json'
            r = requests.get(url=api_url, headers=headers, auth=(self.username, self.api_token), verify=ssl.CERT_NONE)

            return r.json()
        except Exception as e:
            print("Error occurred: ", str(e))
        finally:
            if r is not None:
                r.close()

Please remember that requests is not in the standard library, so you may need to install it with pip. Another thing to note is that I could not figure out a proper way to verify the SSL cert. I tried many things but I was spending too much time so I’m setting verify=ssl.CERT_NONE. I’m hoping to figure it out later when I have more time.

Here is the sample test code.

    def test_get_jobs(self):
        jenkins = jenkins_server("https://jks.westus.cloudapp.azure.com", "yourusername", "api token here")
        jobs = jenkins.get_jobs()
        for job in jobs['jobs']:
            print(f"name: {job['name']}")

Here is the output from the sample code.

name: build-jenkins-toolset-dev
name: linux-prod
name: linux-test
name: pipeline-test
name: win-test

I will dig deeper in Jenkins API with Python later in my blog.

Author: admin

A software engineer in greater Seattle area

Leave a Reply

Your email address will not be published. Required fields are marked *