2017-10-12 106 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