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

时间:2018-07-24 07:34:04

标签: jenkins groovy jenkins-pipeline groovyshell

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

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

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

我想将相同的响应捕获到变量中,然后将该响应用于进一步的操作

下面是我的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
                }
            }
        }
    }
}

能告诉我我的Jenkinsfile文件需要做哪些更改

1 个答案:

答案 0 :(得分:6)

如果您想从sh步骤返回输出并将其捕获到变量中,则必须进行更改:

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

收件人:

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

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