我正在设置 Jenkins 管道构建,并开始在多个作业中使用相同的方法,因此是时候将这些通用方法放入共享库中了。
我创建的第一个函数是使用一些单元测试的结果更新 GitHub。我遇到一个问题,我可以从命令行很好地运行此函数,但是当在我的 Jenkins 构建中使用它时,它不起作用,并且我似乎无法在 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
}
}
我可以通过命令行很好地运行这个程序,但是当作为 Jenkins 构建运行时我没有得到任何输出。
我的 Jenkins 文件
@Library('echo-jenkins-shared')_
node {
GIT_COMMIT_ID = getGitCommitId()
echo "GIT COMMIT ID: ${GIT_COMMIT_ID}"
gitUpdateStatus(GIT_COMMIT_ID)
}
为什么这不起作用或者可以将其转换为仅使用 native Groovy 方法?
最佳答案
首先,我建议您使用像 https://requestb.in 这样的服务检查您的代码是否实际执行 HTTP 调用。
其次,我建议不要在 Jenkins 管道中使用基于 @Grab
的依赖项,例如 HTTPBuilder
,而是使用 http_request
插件,可下载& 可安装为 .hpi
:
https://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
关于java - 无法运行共享 Groovy 库函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46712212/