我正在尝试在 Groovy 中创建一个库,可以从 Jenkins 创建 JIRA 问题。我能够创建问题,但如何将函数输出重定向到变量以从显示在控制台上的 json 输出中过滤特定的键/值?
控制台输出从我想要导出的位置打印如下,
id
和key
[Pipeline] sh (hide)
...
...
{"id":"89000","key":"MyKEY-12","self":"https://MyORG.atlassian.net/rest/api/2/issue/89000"}
这是我创建的库函数
def call(Map config=[:]) {
def rawBody = libraryResource 'com/org/api/jira/createIssue.json'
def binding = [
key: "${config.key}",
summary: "${config.summary}",
description: "${config.description}",
issuetype: "${config.issuetype}"
]
def render = renderTemplate(rawBody,binding)
def response = sh('curl -D- -u $JIRA_CREDENTIALS -X POST --data "'+render+'" -H "Content-Type: application/json" $JIRA_URL/rest/api/2/issue')
return response
}
这是我调用函数的管道
@Library("jenkins2jira") _
pipeline {
agent any
stages {
stage('create issue') {
steps {
jiraCreateIssue(key: "MyKEY", summary: "New JIRA Created from Jenkins", description: "New JIRA body from Jenkins", issuetype: "Task")
}
}
}
}
要实现您想要的效果,只需修改
sh
步骤以返回输出,然后将其读取为 JSON 并将其转换为将由您的函数重新调整的字典。
例如,您可以将 jiraCreateIssue.groovy 更改为:
def call(Map config=[:]) {
def rawBody = libraryResource 'com/org/api/jira/createIssue.json'
def binding = [
key: config.key,
summary: config.summary,
description: config.description,
issuetype: config.issuetype
]
def render = renderTemplate(rawBody,binding)
def response = sh script:'curl -D- -u $JIRA_CREDENTIALS -X POST --data "render" -H "Content-Type: application/json" $JIRA_URL/rest/api/2/issue', returnStdout: true
def dict = readJSON text: response
return dict // return a dictionary containing all the response values
}
** 使用管道实用程序步骤插件中的 readJSON 步骤。
比在您的管道中您可以使用结果:
stage('create issue') {
steps {
script {
def result = jiraCreateIssue(key: "MyKEY", summary: "New JIRA Created from Jenkins", description: "New JIRA body from Jenkins", issuetype: "Task")
println(result.id) // access the returned id
println(result.key) // access the returned key
}
}
}
就是这样,扔出返回的字典你就可以访问所有需要的响应值。