jenkinsgroovyjenkins-pluginsjenkins-groovyjira-rest-api

How to fetch key/value from library function in Groovy script


I am trying to create a library in Groovy that can create a JIRA issue from Jenkins. I am able to create the issue, but how can I redirect the function output to a variable to filter specific key/value from the json output that is displayed on to the console?

The console output prints like below from where I want to export id and key

[Pipeline] sh (hide)
...
...
{"id":"89000","key":"MyKEY-12","self":"https://MyORG.atlassian.net/rest/api/2/issue/89000"}

This is the library function I have created

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
}

This is the pipeline from where I am calling the function

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

Solution

  • To achieve what you want just modify your sh step to return the output, then read it as JSON and convert it to a dictionary that will be retuned by you function.

    For example you can change you jiraCreateIssue.groovy to:

    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
    }
    

    ** Using the readJSON step from the pipeline utility steps plugin.
    Than in your pipeline you can use the result:

    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
            }
        }
    }
    

    That's it, threw the returned dictionary you can access all needed response values.