DelboyJay DelboyJay - 4 months ago 25
Python Question

Add build information in Jenkins using REST

Does anyone know how to add build information to an existing Jenkins build?

What I'm trying to do is replace the #1 build number with the actual full version number that the build represents. I can do this manually by going to http://MyJenkinsServer/job/[jobname]/[buildnumber]/configure

I have tried to reverse engineer the headers using chrome by seeing what it sends to the server and I found the following:

Request URL:http://<server>/job/test_job/1/configSubmit
Request Method:POST
Status Code:200 OK

Request Headers view source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:192
Content-Type:application/x-www-form-urlencoded
Cookie:hudson_auto_refresh=false; JSESSIONID=qbn3q22phkbc12f1ikk0ssijb; screenResolution=1920x1200
Referer:http://<server>/job/test_job/1/configure
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4

Form Data view URL encoded
displayName:#1
description:test4
core:apply:true
json:{"displayName": "#1", "description": "test4", "": "test4", "core:apply": "true"}**

Response Headers view source
Content-Length:155
Content-Type:text/html;charset=UTF-8
Server:Jetty(8.y.z-SNAPSHOT)


This at least gives me the form parameters that I need to POST. So from this I came up with the following python3 code:

import requests
params={"displayName":"Hello World",
"description":"This is my description",
"":"This is my description",
"core:apply":"true"}

a = requests.post("http://myjenkinsserver/job/test_jira_job_update/1/configSubmit", data=params, auth=( username, pwd), headers={"content-type":"text/html;charset=UTF-8"} )
if a.raw.status != 200:
print("***ERROR***")
print(a.raw.status)
print(a.raw.reason)


but sadly this failed with the following error:

***ERROR***
400
Nothing is submitted


Any ideas what I am doing wrong? Is my approach to this problem completely wrong?

Answer

It's a bit confusing to reverse engineer this. You just need to submit the json parameter in your POST:

p = {'json': '{"displayName":"New Name", "description":"New Description"}'}
requests.post('http://jenkins:8080/job/jobname/5/configSubmit', data=p, auth=(user, token))

In my tests, the above works to set the build name and description with Jenkins 1.517.

(Also, I don't think you should set the content-type header, since you should be submitting form-encoded data.)