How to get Jenkins build failure reason using python API

881 Views Asked by At

I want to get the Jenkins build failure reason (Not Status) using the Python API. I searched the Jenkins API and other available modules like, jenkinsapi and Python Jenkins but did not find method which can return failure reason. Another option I could find is Build Failure Analyzer plugin as I cant change anything at Jenkins side its not useful for me. Please suggest.

2

There are 2 best solutions below

2
MortenB On

Just showing the curl since I use the requests.py module directly:

  • lastBuild endpoint to get status of the last build
  • lastSuccessfulBuild to get the last succesful build:
curl.exe -X GET "<your jenkins server>/job/apotek1/job/hso-fullstack-test-test12/lastBuild/api/json" --user jenkinsuser:jenkinspassword | jq.exe

<this show me the last build was 503>

You can then get the console output, but not as json or xml only as html, so you need a way to parse it, adding api/json or api/xml to the end will just say not found:

curl.exe -X GET "<jenkinsserver>/job/apotek1/job/hso-fullstack-test-test12/503/console" --user --user jenkinsuser:jenkinspassword

<!DOCTYPE html><html class=""><head resURL="/static/d949d4e8" \
data-rooturl="" data-resurl="/static/d949d4e8" data-extensions-available="true" \
data-unit-test="false" data-imagesurl="/static/d949d4e8/images" \
data-crumb-header="Jenkins-Crumb" \
data-crumb-value="7b0c0742c71ac08e6c3ea31d2a4b8438a17aa4cbfb86c1bd47ce7633cb4f0f1a">


<title>Fido2 Solutions ,%W% hso-fullstack-test-test12 #503 - test12 -\
ChromeHeadless - failed Console [Jenkins]</title><link rel="stylesheet" \
href="/static/d949d4e8/jsbundles/base-styles-v2.css" type="text/css">
:
0
Carl Walsh On

Look at the docs about the "knowledge base" of historical failure reasons:

The plugin comes with two ways of saving the knowledge base:

  • Local knowledge base. Saves the knowledge base in memory and serializes it as an xml file on the local Jenkins server (i.e. the "standard" Jenkins way of saving information).
  • MongoDB knowledge base. Saves the knowledge base in a Mongo database...

So if you are using the default settings, you might have permission to look at the Jenkins server local file system and find the XML files.

For our Jenkins server we don't have that permission, so we set up a MongoDB database server that Jenkins pushes changes to. Then you can use whatever API you want to read data from the MongoDB.