2017-10-12 112 views
0

我正在設置Jenkins管道構建過程,並開始在多個作業中使用相同的方法,因此是時候將這些常用方法放入共享庫中。無法運行共享Groovy庫函數

我創建的第一個函數是用某些單元測試的結果更新GitHub。我遇到了一個問題,我可以從命令行運行該函數,但是在涉及到在我的Jenkins中使用它時構建它不工作,我似乎無法獲得在詹金斯控制檯

這調試輸出是我的共享庫的目錄結構

my-project 
src 
vars 
    - getCommitId.groovy 
    - gitUpdateStatus.groovy 

所以getCommitId正常工作的第一功能

#!/usr/bin/env groovy 
def call() { 
    commit_id = sh script: 'git rev-parse HEAD', returnStdout: true 
    commit_id = commit_id.replaceAll("\\s","") // Remove Whitespace 
    return commit_id 
} 

這將返回正確的值

這是gitUpdateStatus

#!/usr/bin/env groovy 
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7') 

import static groovyx.net.http.ContentType.JSON 
import static groovyx.net.http.Method.POST 
import groovyx.net.http.HTTPBuilder 


String targetUrl = 'https://api.github.com/repos/myRepo/' 
def http = new HTTPBuilder(targetUrl) 
http.request(POST) { 
    uri.path = "repo/statuses/12345678" 
    requestContentType = JSON 
    body = [state: 'success', description: 'Jenkins Unit Tests', target_url: 'http://test.co.uk', context: 'unit tests'] 
    headers.'Authorization' = "token myOauthTokenHere" 
    headers.'User-Agent' = 'Jenkins Status Update' 
    headers.Accept = 'application/json' 

    response.success = { resp, json -> 
    println "GitHub updated successfully! ${resp.status}" 
    } 

    response.failure = { resp, json -> 
    println "GitHub update Failure! ${resp.status} " + json.message 
    } 
} 

我可以運行通過命令行這很好,但我沒有得到任何輸出運行時作爲詹金斯建立

我Jenkinsfile

@Library('echo-jenkins-shared')_ 
node { 
    GIT_COMMIT_ID = getGitCommitId() 
    echo "GIT COMMIT ID: ${GIT_COMMIT_ID}" 
    gitUpdateStatus(GIT_COMMIT_ID) 
} 

有沒有人有任何想法,爲什麼這不起作用或這可以轉換爲只使用本機Groovy方法?任何指針讚賞

感謝

回答

1

首先,我會建議你使用像https://requestb.in服務來檢查你的代碼實際執行HTTP調用。

其次,我會建議不要使用@Grab基於依賴像詹金斯管道HTTPBuilder,但http_request插件代替,可下載安裝&作爲.hpihttps://jenkins.io/doc/pipeline/steps/http_request/

最後,你可以找到實用的例子類來執行HTTP請求位置: https://github.com/voyages-sncf-technologies/hesperides-jenkins-lib/blob/master/src/com/vsct/dt/hesperides/jenkins/pipelines/http/HTTPBuilderRequester.groovy 隨着理由背後解釋有:https://github.com/voyages-sncf-technologies/hesperides-jenkins-lib#httprequester

+0

謝謝你的信息,我可以證實,我的代碼並不實際PERFO rm HTTP調用,這是我猜的開始,GET請求工作正常,只是POST我有一分鐘的問題 – Richlewis