从地图

时间:2017-12-04 22:32:56

标签: jenkins groovy jenkins-pipeline

我想为我的Jenkins管道共享库提供一个groovy文件,它可以存储几个具有默认值的键,并且能够调用并从不同的groovy函数中获取其他函数的各个键的值,例如 test .groovy作为。我不确定我应该如何构建groovy文件。

/vars/settings.groovy

def configuration = [
    artifactoryURL: 'artifactory.example.com',                          
    daysToKeep: 14,                                             
    maxRetry: 3 ]

/var/test.groovy

globalVariables.get('artifactoryURL')   // I would like this to return "artifactory.example.com"

任何帮助将不胜感激。

更新

我按照以下方式工作:

/vars/settings.groovy

#!/usr/bin/groovy
def getConfig() {
def config = [
    artifactoryURL: 'artifactory.example.com',
    daysToKeep: 14,
    maxRetry: 3
]
return config
}

def getValue(name) {
    return config[name]
}


/vars/retrieveValue.groovy

...
echo "value is " + settings.getConfig()
echo "new value is " + settings.getValue('artifactoryURL')
...

输出:

value is [artifactoryURL:artifactory.example.com, daysToKeep:14, maxRetry:3]
new value is artifactory.example.com

这是正确的语法吗? 有没有办法简化这些?

2 个答案:

答案 0 :(得分:1)

问题中的更新有效,但并非最佳,因为getter每次都会创建一个新的config地图。以下应该有效并且应该更好。请注意,由于Groovy会自动创建吸气剂,因此不需要显式getConfig

$ cat vars/settings.groovy

import groovy.transform.Field

@Field static config = [
    artifactoryURL: 'artifactory.example.com',
    daysToKeep: 14,
    maxRetry: 3
]

def getValue(name) {
    return config[name]
}


$ cat vars/retrieveValue.groovy

...
echo "value is " + settings.getConfig()
echo "new value is " + settings.getValue('artifactoryURL')
...

实际上,config应该是公开的并且可以无障碍地访问,并且getValue可以通过以下方法被认为是多余的:

$ cat vars/settings.groovy

import groovy.transform.Field

@Field static config = [
    artifactoryURL: 'artifactory.example.com',
    daysToKeep: 14,
    maxRetry: 3
]

def call(name) {
    return config[name]
}


$ cat vars/retrieveValue.groovy

...
echo "value is " + settings.config
echo "new value is " + settings('artifactoryURL')
...

答案 1 :(得分:0)

使用config file Provider Plugin

  • 在Jenkins中设置配置文件>管理Jenkins>托管文件

    artifactoryURL ="artifactory.example.com"                                  
    daysToKeep =14                                            
    maxRetry =3
    
  • 在Jenkins文件中,您可以调用如下:

    node {
    stage('configFile Plugin') {
    
     def myFileId = 'your_file_id'
     configFileProvider([configFile(fileId: myFileId, variable: 'artifactoryURL')]){
       sh "cat ${env.artifactoryURL}"
     }
    
     }
    }