代码之家  ›  专栏  ›  技术社区  ›  Anand Deshmukh

如何在jenkinsfile中将curl响应捕获为变量

  •  3
  • Anand Deshmukh  · 技术社区  · 6 年前

    我想弯曲一个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
                    }
                }
            }
        }
    }
    

    你能告诉我在我的詹金斯档案里需要做什么修改吗

    1 回复  |  直到 6 年前
        1
  •  6
  •   Szymon Stepniak    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