【问题标题】:jenkinsfile variable scopejenkinsfile 变量范围
【发布时间】:2018-05-25 02:27:55
【问题描述】:

我正在尝试将远程作业从一个 Jenkins 服务器调用到另一个,我通过 shell 脚本可以正常工作。但是,尝试将其翻译成 Jenkinsfile 会给我带来问题。在舞台内部使用时,环境变量始终为“null”,即使 this 文章说它应该是全局可用的?

pipeline {
agent any
/* get crumb for CSRF */
environment {
        def crumb = sh 'curl https://jenkins-remote/crumbIssuer/'
}

stages {
/* call remote job */
    stage("remote") {
        steps {
            sh "curl -X POST -H ${env.crumb} https://jenkins-remote/buildWithParameters?foo"
        }
    }
}
}

修剪后的输出如下所示:

[remote_pipeline] Running shell script
+ curl -X POST -H null

我正在使用 Jenkins v2.89.4,新的“管道”作业,“管道脚本”。

【问题讨论】:

  • 你需要做 def crumb = 'jenkins-remote/crumbIssuer' 而不是 def crumb = sh 'some value' 因为这将执行 shell 命令并且不会在 crumb 中存储任何值

标签: jenkins groovy jenkins-pipeline


【解决方案1】:

感谢@TrafLaf 指出变量为空,因为它没有设置为 curl 命令的输出。我的 hacky 解决方案是这样的:

environment {
    def crumbRequest = sh 'curl https://jenkins-remote/crumbIssuer/ > crumbHeader'
    crumbHeader = readFile('crumbHeader').trim()
}

【讨论】:

    【解决方案2】:

    根据官方文档,这是定义环境变量的方式。

    pipeline {
        agent any
    
        environment {
            DISABLE_AUTH = 'true'
            DB_ENGINE    = 'sqlite'
        }
        stages {
            stage('Build') {
                steps {
                    echo "${env.DB_ENGINE}" # to access
                }
            }
        }
    }
    

    但是你写错了,

    environment {
        def crumb = sh 'curl https://jenkins-remote/crumbIssuer/'
    }
    

    所以请完成剩下的工作。

    【讨论】:

      【解决方案3】:

      sh 任务现在可以返回输出,所以理论上以下应该可以工作(未经测试):

      environment {
          crumb = sh(script: 'curl https://jenkins-remote/crumbIssuer/',
              returnStdout: true).trim()
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-10
        • 2014-01-31
        • 2011-02-10
        • 2020-02-07
        • 2012-12-23
        相关资源
        最近更新 更多