Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How catch curl response into variable in Jenkinsfile

I want to curl an URL and capture the response into a variable.

when I curl a command and echo its output I get the correct response as below

sh 'output=`curl https://some-host/some-service/getApi?apikey=someKey`;echo $output;'

I want to catch the same response into a variable and use that response for further operation

Below is my Jenkinsfile

pipeline {
    agent {
          label "build_2"
       }
    stages {
        stage('Build') {
            steps {
                checkout scm
                sh 'npm install'

            }
        }
        stage('Build-Image') {
            steps {
                echo '..........................Building Image..........................'

                //In below line I am getting Output
                //sh 'output=`curl https://some-host/some-service/getApi?apikey=someKey`;echo $output;'

                script {
                    //I want to get the same response here
                    def response = sh 'curl https://some-host/some-service/getApi?apikey=someKey'
                    echo '=========================Response===================' + response
                }
            }
        }
    }
}

Can you please tell me what changes I need to do in my Jenkinsfile

like image 604
Anand Deshmukh Avatar asked Jul 24 '18 07:07

Anand Deshmukh


People also ask

How do you get curl response in 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.

How do you get curl response?

By sending a Curl HEAD request along with the --http2 command line parameter, you can check if the target URL supports the HTTP/2 protocol. In the response, you will see the HTTP/2 200 status line if your server supports the HTTP/2 protocol or HTTP/1.1 200 otherwise.

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.


1 Answers

If you want to return an output from sh step and capture it in the variable you have to change:

def response = sh 'curl https://some-host/some-service/getApi?apikey=someKey'

to:

def response = sh(script: 'curl https://some-host/some-service/getApi?apikey=someKey', returnStdout: true)

Reference: https://jenkins.io/doc/pipeline/steps/workflow-durable-task-step/#sh-shell-script

like image 181
Szymon Stepniak Avatar answered Sep 22 '22 17:09

Szymon Stepniak