How to trigger authenticated Jenkins job with file parameter using standard Python library How to trigger authenticated Jenkins job with file parameter using standard Python library jenkins jenkins

How to trigger authenticated Jenkins job with file parameter using standard Python library


We can do it with the help of requests library only.

import requestspayload = ( ('file0', open("FILE_LOCATION_ON_LOCAL_MACHINE", "rb")),             ('json', '{ "parameter": [ {                                          "name":"FILE_LOCATION_AS_SET_IN_JENKINS",                                          "file":"file0" }]}' ))resp = requests.post("JENKINS_URL/job/JOB_NAME/build",                    auth=('username','password'),                    headers={"Jenkins-Crumb":"9e1cf46405223fb634323442a55f4412"},                    files=payload )

Jekins-Crumb if required can be obtained using:

requests.get('http://username:password@JENKINS_URL/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)')


I found a solution, using the requests and urllib3 libraries. Not entirely standard, but more lightweight than the PycURL dependency. It should be possible to do this directly with requests (avoiding the urllib3 part), but I ran into a bug.

import urllib3, requests, jsonurl = "https://myjenkins.com/job/myjob"params = {"parameter": [    {"name": "integration.xml", "file": "file0"},    ]}with open("integration.xml", "rb") as f:    file_data = f.read()data, content_type = urllib3.encode_multipart_formdata([    ("file0", (f.name, file_data)),    ("json", json.dumps(params)),    ("Submit", "Build"),    ])resp = requests.post(url, auth=("myuser", "mypassword"), data=data,        headers={"content-type": content_type}, verify=False)resp.raise_for_status()


If you are familiar with python, then you can use the jenkins REST APT python wrapper provided by the official site. see this link.

Trigger a build is unbelievably easy by using this python wrapper. Here is my example:

#!/usr/bin/pythonimport jenkinsif __name == "main":    j = jenkins.Jenkins(jenkins_server_url, username="youruserid", password="yourtoken")    j.build_job(yourjobname,{'param1': 'test value 1', 'param2': 'test value 2'},                    {'token': "yourtoken"})

For those who don't know where to find the token, here is how:

login to jenkins -> click your userid from the top of the webpage -> Configure ->Show API Token...

Enjoy it.