Search code examples
curljenkins-pipelinehttp-post

How to pass json body to curl command from jenkins pipeline in groovy


It seems like impossible to pass a string that represents json body for POST request with curl using sh command inside Jenkins Pipeline.

I have the following sh line inside a pipeline step:

def apiCmd = 'curl -X POST --user user:passe --data  \\"{\\"state\\":\\"' + stateStr + '\\",\\"context\\":\\"branch-regression\\"}\\"' + " --url ${Configuration.CommitStatusUpdateURL}

now what Jenkins actually runs is:

curl -X POST --user user:pass--data '""state":"failure""' '""context":"branch-regression""' --url someurl

What is so annoying is that if you want to run the post request with native groovy Jenkins complaints about security stuff.. and if you try with Curl then the JSON isn't parsed well


Solution

  • Try this:

    def curlOut = sh script: """curl -X POST --user user:passe --data '{"state":"${stateStr}", "context": "branch-regression"}' --url ${Configuration.CommitStatusUpdateURL} """, returnOutput: true
    

    For the future, you can go to your Jenkins script console (at your.jenkins.url/script) and run e.g. this:

    def stateStr = "OK"
    def Configuration_CommitStatusUpdateURL = "https://www.x.com/"
    println """curl -X POST --user user:passe --data '{"state":"${stateStr}", "context": "branch-regression"}' --url ${Configuration_CommitStatusUpdateURL} """ 
    

    Result:

    curl -X POST --user user:passe --data '{"state":"OK", "context": "branch-regression"}' --url https://www.x.com/