Thursday, January 6, 2022

[SOLVED] Curl status response treatment on Jenkins, unable to abort pipeline execution

Issue

I have a scripted pipeline (Jenkinsfile) where I want to grab a CURL response (if 200 ok, move on. Otherwise, abort the job). I`m struggling with the curl syntax within the pipeline stage meant for that:

stage('Getting getting external API') {
steps {
  script{
        /* groovylint-disable-next-line LineLength */
        final String url = "curl -X 'GET' \ 'https://my-endpoint-test/operations/promote/Approved' \ -H 'accept: */*'"


        final def (String code) = sh(script: "curl -s -w '\\n%{response_code}' $url", returnStdout: true)
                    
                    echo "HTTP response status code: $code"
                    /* groovylint-disable-next-line NestedBlockDepth */
                    if (code != "200") {
                        error ('URL status different of 200. Exiting script.')
                    } 
        }
    }
}

I think I`m not in the right direction with this URL, it complains about the ""after GET and before "-H".

    WorkflowScript: 54: unexpected char: '\' @ line 54, column 47.

   l String url = "curl -X 'GET' \ 'https:/

                                 ^1 error

Also, could you advise on a more simple way of aborting this pipeline, depending on the http status response?


Solution

Your curl cmd is incorrect.

stage('Getting getting external API') {
  steps {
    script{

      cmd = """
          curl -s -X GET -H 'accept: */*' -w '{http_code}' \
              'https://my-endpoint-test/operations/promote/Approved' 
      """

      status_code = sh(script: cmd, returnStdout: true).trim()
      // must call trim() to remove the default trailing newline
                  
      echo "HTTP response status code: ${status_code}"

      if (status_code != "200") {
          error('URL status different of 200. Exiting script.')
      } 
    }
  }
}


Answered By - yong