Skip to content
Advertisement

Run Jenkins Job In Python Using Token

I want to run Jenkins job with the use of tokens. But this piece of code gives 403 error.

How to avoid this problem? I will not use username and password, Only token. Is there any way to do this?

Code:

import requests
try:
    build = requests.get("http://jenkins_url/jenkins_job_name/build?token=TokenFromJob")
except Exception as e:
    print ("Failed triggering the Jenkins job")
print (build.status_code)

Advertisement

Answer

Refer to this. Jenkins doesnt do authorization. So even after you have generated authorization key you need to handle authorization in your python script.

Note that Jenkins does not do any authorization negotiation. i.e. it immediately returns a 403 (Forbidden) response instead of a 401 (Unauthorized) response, so make sure to send the authentication information from the first request (aka “preemptive authentication”).

Here is what i have in my setup. Need To pass username and api token as below. You do not need to pass token to the build url once you are logged in.

import requests
from requests.auth import HTTPBasicAuth

session = requests.Session()
login_response = session.post(JENKINS_URL,auth=HTTPBasicAuth(USERNAME,API_TOKEN))
# check is status code is successfull
# then do other things
build = requests.get("http://jenkins_url/jenkins_job_name/build")
print (build.status_code)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement