Home > Enterprise >  Save curl Response in a varaible in Jenkins declarative pipeline
Save curl Response in a varaible in Jenkins declarative pipeline

Time:09-27

I have a Jenkins decalarative pipeline where I am calling some URL via cURL which is returning JSON response. How to catch that JSON in a variable?

Have tried the below code but it's returning entire thing with path and command along with the response

environment {
        token = bat(returnStdout: true, script: 'curl https://anypoint.mulesoft.com/accounts/login -H "Content-Type: application/json" -d "{\\"username\\" : \\"user\\",\\"password\\" : \\"pwd\\"}"').trim()
        }

JSON Response -

{
  "access_token": "1e54509d-c67f-4833-9445-802eced67e11",
  "token_type": "bearer",
  "redirectUrl": "/home/"
}

JSON response -2

C:\ProgramData\Jenkins\.jenkins\workspace\publish-api>curl https://anypoint.mulesoft.com/accounts/login -H "Content-Type: application/json" -d "{\"username\" : \"ap-1\",\"password\" : \"Ap5\"}" 
{
  "access_token": "abe9f24b-5ca2-48eb-9eb3-173c44a811",
  "token_type": "bearer",
  "redirectUrl": "/home/"
}

CodePudding user response:

You can use the readJson method to get to your wished result. You don't necesseraly have to call it in your environment-block.

stage('Curl') {
  steps {
   script {
    def cUrlResponse = bat(returnStdout: true, script: '@curl https://anypoint.mulesoft.com/accounts/login -H "Content-Type: application/json" -d "{\\"${env.username}\\" : \\"user\\",\\"${env.password}\\" : \\"pwd\\"}"').trim()
    def responseJson = readJSON text: cUrlResponse 
    def accessToken = responseJson.access_token
    def tokenType = responseJson.token_type
    // do other stuff with the variables
   }
  }
}

To exclude the curl command from the output, add @ in front of the script as stated in the documentation.

  • Related