Last Updated: February 25, 2016
·
427
· wehappyfew

Stealing the current Github branch name from Jenkins

Yeah, you read right. Stealing. Cause I can not describe it better.

Something that ought to be plain simple took me 2 hours of searching and eventually some more time building.

I wanted the name of the branch that is NOW on Jenkins waiting to be built.

I searched on Google, StackEverything, blogs, Python APIs for Jenkins on Github but in vain.

Finally I decided to DoItMYself.

This is want I end up with and it works like a charm! :]

__author__ = 'wehappyfew'


# the url of jenkins config.xml
jenkins_url = 'http://11.11.111.11:8686/job/TheJob/config.xml'
j_user = "someone"
j_pass = "somepass"

def get_jenkins_branch_name(jenkins_url, j_user, j_pass):
    """
        The function goes to the provided jenkins XML url,
         authenticates with an authenticated user,
         grabs the xml,
         turns it to dictionary,
         searches inside the dictionary for the branch name
    """
    import requests,xmltodict
    from requests.auth import HTTPBasicAuth

    # get the url with an authenticated user
    response = requests.get(jenkins_url, auth=HTTPBasicAuth(j_user, j_pass)) #the response must be 200

    # the content of the response is the xml
    xml = response.content

    # parse the xml to a dictionary
    jenkins_dict = xmltodict.parse(xml)

    # grab the actual branch name
    branch_name = jenkins_dict['project']['scm']['branches']['hudson.plugins.git.BranchSpec']['name']

    return branch_name