我对詹金斯有一个问题。我发了一个http请求,这会给我一个像这样的json文件:
httpRequest authentication: 'b689fe3c-117e-4076-b10d-fe16ab14742f', httpMode: 'POST', outputFile: 'merge.json', responseHandle: 'NONE', url:'http://address:port/prweb/api/v1/branches/TestB/merge'
{ "ID": "SYSTEM-QUEUE-MERGE 50304628545400035CA951969013040610A435733ECEAE8",
"pxObjClass": "Pega-API-CI-Branch",
"statusValue": "OK"
}
我想要在其他http请求中使用该ID:
http://address:port/prweb/api/v1/merges/{$ID}
我尝试像这样捕获Id:ID = $(cat merge.json | grep -o SY。* [a-z](所有json文件都相同)
我尝试在sh管道中捕获ID但是他没有工作,所以我尝试在步骤上定义,和以前一样。如果有人有解决方案,它对我来说会很棒! 我继续搜索,如果我成功,我将编辑
编辑:我的管道代码:
pipeline{
agent any
stages{
stage ('Merge Branch') {
steps{
httpRequest authentication: 'b689fe3c-117e-4076-b10d-fe16ab14742f', httpMode: 'POST', outputFile: 'merge.json', responseHandle: 'NONE', url: 'http://address:port/prweb/api/v1/branches/TestB/merge'
httpRequest authentication: 'b689fe3c-117e-4076-b10d-fe16ab14742f', httpMode: 'GET', outputFile: 'merge3.json', responseHandle: 'NONE', url: 'http://address:port/prweb/api/v1/merges/'
}
}
}
}
答案 0 :(得分:0)
grep并不适合我。我相信你可以让它充分搞乱。
如果您安装jq,您可以执行以下操作:
ID="$(cat merge.json | jq -r .ID)"
# produces SYSTEM-QUEUE-MERGE 50304628545400035CA951969013040610A435733ECEAE8
# as expected
echo "$ID"
当然即使你成功获得shell解析的输出,你仍然需要将结果返回到groovy上下文才能使用httpRequest
。一个热门的解决方案是完全避免使用httpRequest
,只使用curl来处理三个请求。 :)这种方法(使用外部脚本为您的构建)可能是不直观的,由詹金斯人提倡。
如果你必须将http请求保存在groovy中,这里有一个完整的管道来回答你的问题:
pipeline {
agent { label 'docker' }
stages {
stage('build') {
steps {
script {
def idFromJson = sh(script: "cat merge.json | jq -r .ID", returnStdout: true).trim()
# produces output: idFromJson: SYSTEM-QUEUE-MERGE 50304628545400035CA951969013040610A435733ECEAE8
echo "idFromJson: ${idFromJson}"
}
}
}
}
}
答案 1 :(得分:0)
我认为最简单的方法是使用jenkins管道中的readJson插件:
pipeline{
agent any
stages{
stage ('Merge Branch') {
steps{
httpRequest authentication: 'b689fe3c-117e-4076-b10d-fe16ab14742f', httpMode: 'POST', outputFile: 'merge.json', responseHandle: 'NONE', url: 'http://address:port/prweb/api/v1/branches/TestB/merge'
def jsonResponse = readJSON file: 'merge.json'
httpRequest authentication: 'b689fe3c-117e-4076-b10d-fe16ab14742f', httpMode: 'GET', outputFile: 'merge3.json', responseHandle: 'NONE', url: "http://address:port/prweb/api/v1/merges/${jsonResponse.ID}"
}
}
}
您也可以阅读响应内容而不是保存到文件中:
pipeline{
agent any
stages{
stage ('Merge Branch') {
steps{
def response = httpRequest authentication: 'b689fe3c-117e-4076-b10d-fe16ab14742f', httpMode: 'POST', responseHandle: 'NONE', url: 'http://address:port/prweb/api/v1/branches/TestB/merge'
def jsonResponse = readJSON text: "${response.content}"
httpRequest authentication: 'b689fe3c-117e-4076-b10d-fe16ab14742f', httpMode: 'GET', outputFile: 'merge3.json', responseHandle: 'NONE', url: "http://address:port/prweb/api/v1/merges/${jsonResponse.ID}"
}
}
}