首页 > 解决方案 > 将 Jenkinsfile 中属性文件的值替换为动态设置的变量

问题描述

我有一个 Jenkinsfile,其中包含多个特定于环境的参数。

这些参数的值存储在属性文件中。我正在尝试根据所选环境设置变量,然后从属性文件中替换它们的值。

詹金斯文件

ENVIRONMENT 是具有 2 个值的选择参数:ft、perf 和 pm,如下所示在我的 Jenkinsfile

choice (
        name: 'ENVIRONMENT',
        choices: ['ft', 'perf','pm'],
        description: 'please select the environment'
        )

PROPERTY_FILE 是另一个选择参数,如下所示

 choice (
        name: 'PROPERTY_FILE',
        choices: ['jenkins/app.groovy'],
        description: 'please select the property file'
        )

app.groovy 看起来像:

Test_perf="Hello"
Test_ft="World"
Test_pm="Welcome"

阶段

stage('Load Environment Property File') {
                    steps {
                        script {
                                //sourcing user selected property file
                                load "${PROPERTY_FILE}"
                                def envName = "${PROPERTY_FILE}".tokenize(".")[0]
                                //it will set build description as description in Jenkins build history
                                env.envName=envName
                                currentBuild.description = "Env:${envName}"
                                }
                          }
                }
                

//我需要帮助的阶段

stage('Set Variables Based upon environment name') {
                    steps {
                           script{
                                if ("${ENVIRONMENT}" ==  "perf" ){
                                    var="\${Test_"+"${DEPLOYMENT_ENVIRONMENT}"+"}"
                                    echo "${var}" //output is ${Test_pm} and is correct as the substitution happens.
                                    //NOW, I AM TRYING TO echo "HELLO", i.e.; replacing the variable "${Test_perf}" stuffed inside "var" from the property file. However, since the property file is already loaded, it will not replace the key by its value from the property file.
                                } else if ("${ENVIRONMENT}" ==  "ft" ){
                                    var="\${Test_"+"${DEPLOYMENT_ENVIRONMENT}"+"}"
                                    echo "${var}" //output is ${Test_ft} and is correct as the substitution happens.
                                    //NOW, I AM TRYING TO echo "World" 
                                } else {
                                    var="\${Test_"+"${DEPLOYMENT_ENVIRONMENT}"+"}"
                                    echo "${var}" //output is ${Test_pm} and is correct as the substitution happens.
                                    //NOW, I AM TRYING TO echo "Welcome"
                                } 
                            }

                    }
                }

有没有办法进一步替换属性文件中的值。例如;"${var}" 扩展为 "${Test_pm}",然后 "${Test_pm}" 从属性文件中获取值 "Welcome"。请帮忙。

标签: groovyjenkins-pipelinejenkins-groovyjenkins-declarative-pipeline

解决方案


推荐阅读