Using groovy to parse JSON object in shell scripts for Jenkin

此生再无相见时 提交于 2020-12-12 12:09:26

问题


Say I have a JSON as following:

{"id":"1.0.0-6",
"version":"1.0.0",
"build":6,
"tag":"android-v1.0.0-6",
"commitHash":"5a78c4665xxxxxxxxxxe1b62c682f84",
"dateCreated":"2020-03-02T08:11:29.912Z"}

I want to take out the version id from it in Jenkins Groovy file and pass the version id to a JIRA Plugin called XRAY so that it will create a build version as Label in JIRA.

stage('Get App version') {
      steps {
          container('devicefarm') {
               steps {
                   sh "LATEST_VERSION=$(curl ${APP_ARTIFACTORY_URL}/${XRAY_PLATFORM}/builds/latest.json | sed \"s/.*$VERSION_KEY\":\"\\([^\"]*\\).*/'\\1'/\")"
               }
           }
      }
}
environment {
        AWS_DEFAULT_REGION = 'uk-xxx'
        XRAY_ENVIRONMENT = 'e2e'
        VERSION_KEY = 'id'
        XRAY_PLATFORM = 'Android'
        APP_ARTIFACTORY_URL = 'https://artifactory.example.com/mobile'
        LATEST_VERSION = ''
}

I have two questions, will the result of curl command been assigned to variable defined in the same Jenkins file called 'LATEST_VERSION' as expected?

I probably can test it by running the pipe line on Jenkins but I got another issue that prevent me from doing this, it complains that 'Identifier or code block expected'.

While running same in a sh file, it doesn't have this issue, version id was retrieved from JSON as expected.


回答1:


There are a few steps to achieving this. First, we need to fix your shell method execution. We will convert it into a valid shell execution that returns the standard out of the execution and assigns it to a variable:

build_json = sh(label: 'Retrieve Build Info', script: "curl ${APP_ARTIFACTORY_URL}/${XRAY_PLATFORM}/builds/latest.json", returnStdout: true)

This is a valid shell method execution that will also return the standard out and assign it to a variable. See the documentation for more information.

Next, we need to parse the resulting JSON, and assign that return value to a variable:

build_map = readJSON(text: build_json)

See the documentation for more information.

Finally, we now have a Map where we can access the value for the latest_version key and assign it to a variable. We can access with this syntax:

latest_version = build_map['version']

or this:

latest_version = build_map.version

Note that while this does answer your question, you cannot pass dynamic values to an environment block during the pipeline execution (which your question implies you want to perform later). So, you are going to need try a different route for that, and may need to ask a followup question about it.



来源:https://stackoverflow.com/questions/61654487/using-groovy-to-parse-json-object-in-shell-scripts-for-jenkin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!