如何使用从属性文件设置的 groovy 变量?

问题描述 投票:0回答:1

我有这个简单的属性文件

a=1
b=2

以及以下常规代码

    stage('Load Properties') {
        steps{
            script{
                props = readProperties file:"application.properties"
                keys= props.keySet()
                for(key in keys) {
                    value = props["${key}"]
                    env."${key}" = "${value}"
                }
            }
        }
    }
    stage('Use Properties') {
        steps{
                script {
                    println "a: ${a}"
                    sh '''
                        echo "a: ${a}"  
                    '''
                }
            }
        }
    }

但是输出没有任何意义:

[Pipeline] script
[Pipeline] {
[Pipeline] echo
a: 1
[Pipeline] sh
+ echo 'a: '
a: 

echo "a: ${env.a}" 只返回 "${env.a}: 错误替换"

groovy jenkins-pipeline
1个回答
0
投票

这里有各种语法、范围和使用问题,我们可以修复:

stage('Properties') {
  steps {
    script {
      Map props = readProperties(file: 'application.properties')
      for(key in props.keySet()) {
        env[key] = props[key]
      }
      // note this resolve the properties variable value since it is Groovy interpreted ...
      println "a: ${a}"
      // ... and this resolve the environment variable value since it is shell interpreted
      sh 'echo "a: ${a}"'
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.