首页 > 解决方案 > Jenkins上的卷曲状态响应处理,无法中止管道执行

问题描述

我有一个脚本管道(Jenkinsfile),我想在其中获取 CURL 响应(如果 200 ok,继续。否则,中止工作)。我正在为管道阶段的 curl 语法苦苦挣扎:

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.')
                    } 
        }
    }
}

我认为这个 URL 的方向不对,它抱怨“GET 之后和“-H”之前的“”。

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

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

                                 ^1 error

另外,您能否建议一种更简单的中止此管道的方法,具体取决于 http 状态响应?

标签: curlgroovyjenkins-pipeline

解决方案


您的 curl cmd 不正确。

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.')
      } 
    }
  }
}

推荐阅读