How to get Build status of Jenkins Job using python script (Video)


Most of us might have gone through situations where we need to check status of a Jenkins  Job and do some automations based on it. In this article, let me get you through steps on how you can check build status of last Jenkins job using Python script.

Step1: Use Jenkins API:

Yeah, Jenkins has an API which gives building status, Last Job build status(failed or Success) and some other useful information in JSON  format. This is the API /job/your_job_name_here/lastBuild/api/json .

Video Demonstration:

Please LIKE , COMMENT  and SUBSCRIBE .


[do_widget id=custom_html-12]

Let use curl  command to see the result of the API.

curl https://your_jenkins_endpoint/job/testjob/lastBuild/api/json

Here is the JSON result. I have hidden results which are not relevant for this article.

{  
   "_class":"*********",
   "actions":[  
      {  
         "_class":"***************",
         "parameters":[  
            {  
               "_class":"*********",
               "name":"regex",
               "value":"**********"
            },
            {  
               "_class":"*********",
               "name":"*********",
               "value":"*********"
            },
            {  
               "_class":"*********",
               "name":"*********",
               "value":"*********"
            },
            {  
               "_class":"*********",
               "name":"*********",
               "value":"*********"
            }
         ]
      },
      {  
         "_class":"*********",
         "causes":[  
            {  
               "_class":"*********",
               "shortDescription":"*********",
               "userId":null,
               "userName":"anonymous"
            }
         ]
      },
      {  

      }
   ],
   "artifacts":[  

   ],
   "building":false,
   "description":null,
   "displayName":"#4095",
   "duration":2670,
   "estimatedDuration":2513,
   "executor":null,
   "fullDisplayName":"testjob #4095",
   "id":"4095",
   "keepLog":false,
   "number":4095,
   "queueId":22092,
   "result":"SUCCESS",
   "timestamp":1544853780985,
   "url":"*********",
   "builtOn":"",
   "changeSet":{  
      "_class":"*********",
      "items":[  

      ],
      "kind":null
   },
   "culprits":[  

   ]
}

We can use keys building  and result  to achieve our goal. For your information, If value of key building  is True  (it is a boolean) which means requested Job is currently running and if it is False  means the Job is not running now. Like wise, if value of result is SUCCESS , it means last build is success and if it is FAILURE , which means, last build is failed. A better picture is given below.

building: True -> requested Job is currently running.

          False -> requested Job is not running now. 

Result: SUCCESS -> last build is success

        FAILURE -> last build is failed.

 

Step2: Let’s write Python script:

So we have all relevant information to write our Python script. Let’s create a logic. What if the Job is still running when we run the script? the Python script should  wait till the Job is completed and then only it should check the status of the Job(otherwise it gives you status of the last job). How do we do this? We need to write the Python script to check value of building  key, if it is True (which means Job is still running), we need to teach script check again after some time. Python’s WHILE loop  is our mate here. The script should exit the WHILE loop once the value of building  is False  and then check value of result  to understand the status of the Job.

Here is our Python script.

import json
import requests
import time



job_name = "testjob"   #Give your job name here


def jenkins_job_status(job_name):
        
        try:
                url  = "https://your_jenkins_endpoint/job/%s/lastBuild/api/json" %job_name   #Replace 'your_jenkins_endpoint' with your Jenkins URL
                while True:
                        data = requests.get(url).json()
                        if data['building']:
                                time.sleep(60)
                        else:
                                if data['result'] == "SUCCESS":

                                        print "Job is success"
                                        return True
                                else:
                                        print "Job status failed"
                                        return False

                
        except Exception as e:
                print str(e)
                return False




if __name__ == "__main__":

        if jenkins_job_status(job_name):

                print "Put your autmation here for 'job is success' condition"

        else:
                print "Put your autmation here for 'job is failed' condition"                
	

 

The Python script is very straight forward.  The core function jenkins_job_status()  takes the job name as input and returns boolean output as per job status. Go ahead use this script and comment if you are facing any issues.

There could be use-cases like checking status of a remote Jenkins job from another Jenkins Job. There also you can use this script!. Enjoy

 

Subscribe to this blog so that you don’t miss out anything useful (Checkout Right Sidebar for the Subscription Form) . Please also put your thought on this article as a comment .

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top
x