How to make a curl request with json in jenkins pipeline groovy script

限于喜欢 提交于 2020-12-29 05:52:15

问题


I am trying to make a New Relic deployment API call as a Jenkins build step using the Groovy pipeline. I'm having trouble because of the use of both single and double quotes within the shell ('sh') command on the groovy script. Whenever I execute the following:

node {

    //...

    def json = '''\
    {"deployment": {"revision": "v1","user": "me"}}'
    '''

    sh "curl -o /dev/null -s -X POST 'https://api.newrelic.com/v2/applications/[redacted]/deployments.json' \
    -H 'X-Api-Key:[redacted]' \
    -H 'Content-Type: application/json' \
    -d '${json}'"

    // ...
}

I get an error in Jenkins that says:

/var/lib/jenkins/jobs/[redacted]/workspace@tmp/durable-0f6c52ef/script.sh: line 2: unexpected EOF while looking for matching `''


回答1:


The 'json' variable contains a string that has an extra trailing single quote (').

When this is used in -d '${json}'" I suspect it will result in an extra (') in the data block. The data block will require the JSON be enclosed in single quotes so make certain those are included.

Not being a Groovy person (pun intended) you may have to play with escaping characters it ensure that the correct string is passed to the cURL command.




回答2:


I've had a similar issue when I created a job that creates a new repository in Github using Github's API.

I've fixed it by replacing the single ticks with quotes and escaped the quotes inside the json object like so:

curl -H "Authorization: token ${ACCESSTOKEN}" --data "{\"name\":\"${REPONAME}\"}" https://api.github.com/orgs/Company/repos


来源:https://stackoverflow.com/questions/41497385/how-to-make-a-curl-request-with-json-in-jenkins-pipeline-groovy-script

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