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

2

12

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 `''

Unaffected answered 6/1, 2017 at 1:8 Comment(2)
you may also use github.com/jwagenleitner/groovy-wslite#restWirephoto
Thank you for the suggestion on wslite. I tried that but there's a lot more there than I could easily get a handle on.Unaffected
C
7

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.

Coax answered 7/1, 2017 at 0:32 Comment(1)
Thank you. Removing that single quote did work! I also found another solution using Groovy JsonOutput: <code> import groovy.json.JsonOutput def json = JsonOutput.toJson([ deployment : [ revision: "v1", user: "me" ] ])`Unaffected
L
1

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
Luftwaffe answered 19/12, 2019 at 14:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.