如何用 Jenkins API 取得 Job Build Result

當需要建構網頁取得 Jenkins Job 的結果,或是需要整理 Job 狀態並發送通知或郵件的時候,通常會需要透過 API 取得 Job Result

Jenkins API 的 URL : http://jenkinshost:8080/job/[jobName]/[buildNum]/api/json/

但是如果打開 Jenkins Security 設定,使用 API 必須要登入 Jenkins 並有合法的權限
這個時候可以填上 APIToken,便可以登入並使用 API

user 的 APIToken 可以從這個網址找到: http://jenkinshost:8080/user/[myaccount]/configure

以下是完整的實作方法:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import json, urllib, urllib2
from threading import Event

jenkinsMaster = "http://jenkinshost:8080"
userID = "myaccount"
APIToken = "1234567890"

class HTTPBasic403AuthHandler(urllib2.HTTPBasicAuthHandler):
    # retry with basic auth when facing a 403 forbidden
    def http_error_403(self, req, fp, code, msg, headers):
        host = req.get_host()
        realm = None
        return self.retry_http_basic_auth(host, req, realm)

def getBuildResult(jobName, buildNum):
    url_build = jenkinsMaster + "/job/" + jobName + "/" + buildNum + "/api/json"

    auth_handler = HTTPBasic403AuthHandler()
    auth_handler.add_password(
        realm=None,
        uri=jenkinsMaster,
        user=userID,
        passwd=APIToken)
    opener = urllib2.build_opener(auth_handler)
    # install it for all urllib2.urlopen calls
    urllib2.install_opener(opener)

    # retry 5 minutes for unstable network condition
    retryCount = 30
    timeout_event = Event()
    while (reTryCount > 0):
        try:
            jenkinsStream = urllib2.utlopen(url_build)
            reTryCount = 0
        except urllib2.HTTPError as e:
            timeout_event.wait(timeout=10.0)
            reTryCount -= 1

    try:
        jsonData = json.load( jenkinsStream )
    except:
        sys.exit(3)

    return jsonData["result"]

留言

這個網誌中的熱門文章

以樂透為例,用Python統計馬可夫矩陣

將 Jenkins Job 的歷史結果整理出視覺化的 Daily Report mail (一)