Search code examples
jenkinscurljenkins-pipeline

In Jenkins pipeline using curl how can store response cookies?


I'm writing a Jenkins Pipeline using a sh command with curl.

Using a regular command prompt it is possible to store the response cookies and after that sending those cookies in another request, for instance to store the cookies

curl -k -c my_cookies.txt -X POST https://myLogin

and then send a request with those cookies

curl -k -b my_cookies.txt -X GET https://myGetRequest

Is it possible with Jenkins Pipeline to have something similar ?

I have tried something like:

final String url = "https://myLogin"
final String response = sh(script: "curl -c my_cookie.txt -k -X POST $url ", returnStdout: true).trim()

But this generates an error like

curl: (35) Encountered end of file

Any help is appreciated.


Solution

  • It can be done like this :

    pipeline {
        agent any;
        stages {
            stage('call 1st api') {
                steps {
                    sh """
                        curl --cookie-jar $WORKSPACE/cookie.txt https://62e96ddc0c77.ngrok.io/put
                    """
                }
            }
            stage('call 2nd api') {
                steps {
                    sh """
                        curl --cookie $WORKSPACE/cookie.txt https://62e96ddc0c77.ngrok.io/get 
                    """
                }
            }
        }
    }
    

    In the above example if the first call is a success the cookie will store on $WORKSPACE/cookie.txt location and the 2nd call will read it from the same location. $WORKSPACE - is the location of the Job workspace. you no need to hardcode the location, as Jenkins takes care it