Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 438
MarkRoland Avatar asked Jan 06 '17 01:01

MarkRoland


People also ask

How do I get JSON with curl?

To get JSON with Curl, you need to make an HTTP GET request and provide the Accept: application/json request header. The application/json request header is passed to the server with the curl -H command-line option and tells the server that the client is expecting JSON in response.

How do I run curl command in Groovy script?

You could execute the curl command as a shell command using the "execute()" method available on groovy strings. Or you can use some native html processing classes. This will give you some native parsing of the response and response error handling etc.

How do you curl Jenkins pipeline?

The way to execute curl command is to use sh (or bat if you are on the Windows server) step. You need to know that the sh step by default does not return any value, so if you try to assign it's output to a variable, you will get the null value.

Does curl use JSON?

cURL is frequently used by developers working with REST API's to send and receive data using JSON notation.


2 Answers

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
like image 59
Itai Ganot Avatar answered Sep 30 '22 01:09

Itai Ganot


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.

like image 27
REngland Avatar answered Sep 30 '22 02:09

REngland