【问题标题】:Global Variables in Jenkins Shared librariesJenkins 共享库中的全局变量
【发布时间】:2019-08-28 08:31:30
【问题描述】:

我有一个使用共享库的 Jenkinsfile。我想创建一个可在共享库的所有函数中使用的全局变量,类似于params 对象。但是我总是以

groovy.lang.MissingPropertyException: No such property: pipelineParams for class: groovy.lang.Binding

在this guideline 之后,我在Jenkinsfile 中定义了一个Field:

import org.apache.commons.io.FileUtils
@groovy.transform.Field
def pipelineParams

library identifier: 'pipeline-helper@master', retriever: modernSCM(
  [$class: 'GitSCMSource',
       remote: 'https://bitbucket/scm/jenkins/pipeline-helper.git',
       credentialsId: 'bitbucket.service.user'
  ])

defaultCiPipelineMSBuild {
    nodes     = 'TEST-NODES' /* label of jenkins nodes*/
    email     = 'example@example.com' /* group mail for notifications */
    msbuild   = 'MSBUILD-DOTNET-4.6' /* ms build tool to use */ 
}

然后在defaultCiPipelineMSBuild我设置pipelineParams

def call(body) {
    // evaluate the body block, and collect configuration into the object
    pipelineParams= [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = pipelineParams
    body()

    pipeline {
    ...

稍后我会调用一个函数buildApplication 来使用该变量:

def msBuildExe = tool pipelineParams.msbuild

【问题讨论】:

    标签: jenkins groovy jenkins-pipeline


    【解决方案1】:

    您没有尝试自己创建一个全新的管道参数,而是尝试将变量添加到可以在共享库中使用的现有 env 参数中?

    env.param_name = "As per your requirement"
    

    也可以通过env.param_name 或env[param_name] 跨共享库访问

    【讨论】:

    • 这是一个很好的提示,是的,即使对于非字符串也是可能的。我会为这个单独写一个答案
    【解决方案2】:

    正如@Dillip 所建议的,即使对于非字符串也可以使用env。如果存储为环境变量的对象是列表或地图,则应将其反序列化

    所以我稍微更改了管道代码以将地图存储为环境变量

    def call(body) {
        // evaluate the body block, and collect configuration into the object
        pipelineParams= [:]
        body.resolveStrategy = Closure.DELEGATE_FIRST
        body.delegate = pipelineParams
        body()
    
        env.pipelineParams = pipelineParams
    
        pipeline {
        ...
    

    管道是序列化的,因此在读取时返回一个字符串

    { nodes=TEST-NODES,email=example@example.com,msbuild=MSBUILD-DOTNET-4.6 }
    

    因此使用它必须反序列化

    def pipelineParams = 
    // Take the String value between the { and } brackets.
    "${env.pipelineParams}"[1..-2]
        .split(', ')
        .collectEntries { entry -> 
            def pair = entry.split('=')
            [(pair.first()): pair.last()]
        }
    
    //use map
    pipelineParams.msbuild
    

    您可以将反序列化添加到一个函数中,这样您也可以在其他地方使用它。

    【讨论】:

      猜你喜欢
      • 2022-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      相关资源
      最近更新 更多