How to check the build status of a Jenkins build from the command line

command-line-interfaceJenkinsscripting

How do I check the Jenkins build status without switching to the browser?

If required, I can create a script using the JSON API, but I was wondering if there is already something like this built in.

Best Answer

I couldn't find a built in tool so I made one:

#!/usr/bin/python
#
# author: ajs
# license: bsd
# copyright: re2


import json 
import sys
import urllib
import urllib2

jenkinsUrl = "https://jenkins.example.com/job/"


if len( sys.argv ) > 1 :
    jobName = sys.argv[1]
    jobNameURL = urllib.quote(jobName)
else :
    sys.exit(1)

try:
    jenkinsStream   = urllib2.urlopen( jenkinsUrl + jobNameURL + "/lastBuild/api/json" )
except urllib2.HTTPError, e:
    print "URL Error: " + str(e.code) 
    print "      (job name [" + jobName + "] probably wrong)"
    sys.exit(2)

try:
    buildStatusJson = json.load( jenkinsStream )
except:
    print "Failed to parse json"
    sys.exit(3)

if buildStatusJson.has_key( "result" ):      
    print "[" + jobName + "] build status: " + buildStatusJson["result"]
    if buildStatusJson["result"] != "SUCCESS" :
        exit(4)
else:
    sys.exit(5)

sys.exit(0)