groovy 在Jenkins共享库中定义全局变量

daupos2t  于 2022-11-01  发布在  Jenkins
关注(0)|答案(1)|浏览(244)

我在/vars中创建了一个Jenkins共享库,里面有很多函数,其中有一个devopsProperties.groovy,有很多属性:

class devopsProperties {

    //HOSTS & SLAVES
    final String delivery_host = "****"
    final String yamale_slave = "****"

    //GIT
    final Map<String,String> git_orga_by_project = [
        "project1" : "orga1",
        "project2" : "orga2",
        "project3" : "orga3"
    ]
    ...
}

我的共享库中的其他函数使用这些参数。例如gitGetOrga.groovy

def call(String project_name) {
    devopsProperties.git_orga_by_project.each{
        if (project_name.startsWith(it.key)){
            orga_found = it.value
        }
    }
    return orga_found
}

但是现在,由于我们有很多环境,我们需要在管道的开始加载devopsProperties。我在资源中创建了属性文件:

+-resources
 +-properties
  +-properties-dev.yaml
  +-properties-val.yaml
  +-properties-prod.yaml

并创建一个函数来加载它:

def call(String environment="PROD") {
    // load the specific environment properties file
    switch(environment.toUpperCase()) { 
        case "DEV": 
            def propsText = libraryResource 'properties/properties-dev.yaml'
            devopsProperties = readYaml text:propsText
            print "INFO : DEV properties loaded" 
            break
        case "VAL":
            def propsText = libraryResource 'properties/properties-val.yaml'
            devopsProperties = readYaml text:propsText
            print "INFO : VAl properties loaded" 
            break
        case "PROD": 
            def propsText = libraryResource 'properties/properties-prod.yaml'
            devopsProperties = readYaml text:propsText
            print "INFO : PROD properties loaded" 
            break
        default:
            print "ERROR : environment unkown, choose between DEV, VAL or PROD"
            break
    }
    return devopsProperties
}

但当我尝试在管道中使用它时:

@Library('Jenkins-SharedLibraries')_

devopsProperties = initProperties("DEV")

pipeline {
    agent none
    stages {
        stage("SLAVE JENKINS") {
            agent {
                node {
                    label***
                }
            }
            stages{
                stage('Test') {
                    steps {
                        script {
                            print devopsProperties.delivery_host // THIS IS OK
                            print devopsProperties.git_orga_by_project["project1"] // THIS IS OK
                            print gitGetOrga("project1") //THIS IS NOT OK
                        }
                    }
                }
            }
        }
    }
}

最后一次打印产生错误:groovy.lang.MissingPropertyException: No such property: devopsProperties for class: gitGetOrga
如何在Jenkins共享库的所有函数中使用全局变量?如果可能,我不希望在所有函数的参数中传递它。

uyto3xhc

uyto3xhc1#

您需要在gitGetOrga.groovy中导入类

import path/to/devopsProperties.groovy;

def call(String project_name) {
    devopsProperties.git_orga_by_project.each{
        if (project_name.startsWith(it.key)){
            orga_found = it.value
        }
    }
    return orga_found
}

相关问题