Getting Jenkins Jobs Recursively in Python via API

I’ve wanted to come up with a code that can get the whole list of Jenkins jobs recursively. I was able to write it but I’m not really liking it… View it in GitHub.

    def get_jobs(self, recursive=False):
        r = 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 = {'Content-Type': 'application/json'}
            r = requests.get(url=api_url, headers=headers, auth=(self.username, self.api_token), verify=ssl.CERT_NONE)
            jenkins = json.loads(r.text)

            result = {}

            if recursive:
                folders = []
                while True:
                    self.process_result(jenkins['jobs'], folders, result)
                    if len(folders) == 0:
                        break

                    for index, folder in enumerate(folders):
                        r = requests.get(url=f"{folder}api/json", headers=headers,
                                         auth=(self.username, self.api_token), verify=ssl.CERT_NONE)
                        jenkins = json.loads(r.text)
                        self.process_result(jenkins['jobs'], folders, result)
                        folders.pop(index)
                    if len(folders) == 0:
                        break
            else:
                for job in jenkins['jobs']:
                    if job['_class'] != 'com.cloudbees.hudson.plugins.folder.Folder':
                        result[job['url']] = job['name']

            return result
        finally:
            if r is not None:
                r.close()

    def process_result(self, jobs, folders, result):
        for job in jobs:
            if job['_class'] == 'com.cloudbees.hudson.plugins.folder.Folder':
                folders.append(job['url'])
            else:
                result[job['url']] = job['name']

The reason I’m not really liking it because I’m repeating process_result twice in the code. At least I was successful in what I wanted to do and I didn’t use recursive function for recursive result but there has to be a better way to accomplish it. I’m going to dig more into this.

Edit: I realized that the reason why I have repeat the process_result function twice in the code is because Python doesn’t have support do…while. I could be wrong but I’m thinking that’s the core of the issue but if anyone out there can suggest a better way, please let me know. 🙂

Author: admin

A software engineer in greater Seattle area

Leave a Reply

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