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

MarkRoland picture MarkRoland · Jan 6, 2017 · Viewed 23.8k times · Source

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

Answer

REngland picture REngland · Jan 7, 2017

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.