2016-03-10 81 views
3

我有一個Jenkins的工作,名字是Test2,我可以從Jenkins的web界面創建。現在我想用JenkinsAPI觸發該構建。我只能找到示例代碼來執行其他操作,但API Documentation提到了Build類。所以我想我會嘗試實例化它,然後等待它完成(希望這也會觸發實際的構建),但是我比那更早得到相當神祕的錯誤。我究竟做錯了什麼?如何使用Python包JenkinsAPI觸發Jenkins構建?

import jenkinsapi 
b = jenkinsapi.build.Build("http://localhost:8080", 1, "test2") 
b.block_until_complete() 

給我:

Traceback (most recent call last): 
    File "/Users/jonathan/Genetta/Eclipse_Django_workspace/FOO/foo/TriggerBuild.py", line 2, in <module> 
    b = jenkinsapi.build.Build("http://localhost:8080", 1, "test2") 
    File "/Users/jonathan/anaconda/lib/python2.7/site-packages/jenkinsapi/build.py", line 58, in __init__ 
    JenkinsBase.__init__(self, url) 
    File "/Users/jonathan/anaconda/lib/python2.7/site-packages/jenkinsapi/jenkinsbase.py", line 35, in __init__ 
    self.poll() 
    File "/Users/jonathan/anaconda/lib/python2.7/site-packages/jenkinsapi/jenkinsbase.py", line 59, in poll 
    data = self._poll(tree=tree) 
    File "/Users/jonathan/anaconda/lib/python2.7/site-packages/jenkinsapi/build.py", line 65, in _poll 
    return self.get_data(url, params={'depth': self.depth}, tree=tree) 
    File "/Users/jonathan/anaconda/lib/python2.7/site-packages/jenkinsapi/jenkinsbase.py", line 72, in get_data 
    requester = self.get_jenkins_obj().requester 
    File "/Users/jonathan/anaconda/lib/python2.7/site-packages/jenkinsapi/build.py", line 371, in get_jenkins_obj 
    return self.job.get_jenkins_obj() 
AttributeError: 'str' object has no attribute 'get_jenkins_obj' 

回答

3

而不是使用jenkinsapi模塊,你可以觸發你的工作根本要求詹金斯REST API類似如下:

import requests 

# Case job has no parameter 
job_url = "http://localhost:8080/job/test2/build" 

# Job with parameters 
job_url = "http://localhost:8080/job/test2/buildWithParameters?param1=value1&param2=value2" 

status = requests.get(job_url) 
3

這我不清楚爲什麼你示例不起作用,但我發現JenkinsAPI文檔總體上令人困惑,所以也許我只是不明白。

我發現要直接獲取特定版本,您可以在api包中使用get_build method。參數的排列順序不同:

import jenkinsapi 
b = jenkinsapi.api.get_build("http://localhost:8080", "Test 1", 1) 

這對現有構建很好,通過其他方式啓動。但這聽起來像是你真的想要觸發構建。在這種情況下,通過詹金斯實例落榜,並使用invoke方法:

import jenkinsapi 
jenkins = jenkinsapi.jenkins.Jenkins("http://192.168.99.100:8080") 
job = jenkins["Test 1"] 
job.invoke(block=True) 

在我看來,有一點好處是用一個容易混淆的記錄界面包(爲什麼有多種方式來獲取構建? )如果可以通過請求包訪問普通Jenkins REST API,如massiou's answer所述。

相關問題