如何在Groovy脚本中从库函数中获取键/值

um6iljoc  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(77)

我试图在Groovy中创建一个库,可以从Jenkins创建一个JIRA问题。我能够创建问题,但我如何将函数输出重定向到一个变量,以从显示在控制台上的JSON输出中过滤特定的键/值?
控制台输出从我想要导出idkey的位置打印如下

[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")
            }
        }
    }
}

w6mmgewl

w6mmgewl1#

要实现您想要的功能,只需修改sh步骤以返回输出,然后将其读取为JSON并将其转换为将由您的函数返回的字典。
例如,您可以将jiraitsissue.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
        }
    }
}


就是这样,抛出返回的字典,你可以访问所有需要的响应值。

相关问题