如何在Jenkinsfile中捕获卷曲响应变量

Ana*_*ukh 7 groovy groovyshell jenkins jenkins-pipeline

我想卷曲一个URL并将响应捕获到一个变量中.

当我卷曲命令并回显其输出时,我得到正确的响应,如下所示

sh 'output=`curl https://some-host/some-service/getApi?apikey=someKey`;echo $output;'
Run Code Online (Sandbox Code Playgroud)

我想在变量中捕获相同的响应,并使用该响应进行进一步操作

下面是我的Jenkins文件

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
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你能告诉我在Jenkinsfile中需要做些什么改变吗?

Szy*_*iak 15

如果要从sh步骤返回输出并将其捕获到必须更改的变量中:

def response = sh 'curl https://some-host/some-service/getApi?apikey=someKey'
Run Code Online (Sandbox Code Playgroud)

至:

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

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