如何从 Jenkins 2.0 管道脚本读取属性文件

How to read properties file from Jenkins 2.0 pipeline script

我正在尝试编写一个管道脚本以与 Jenkins 2.0 一起使用来复制我们现有的构建。这个原始版本使用 envInject 插件读取 Java 属性文件,但我无法从管道 Groovy 脚本中看到如何执行此操作。我用 Google 搜索并找到了以下内容,但它不起作用 (FileNotFoundException):

Properties props = new Properties()
File propsFile = new File('./Builder/project.properties')
props.load(propsFile.newDataInputStream())

谢谢!

我昨天和今天刚和这个吵过架。我希望它的可用性更容易找到。

获取“Pipeline Utility Steps”插件。

使用 readProperties 步骤。

 def props = readProperties  file: 'dir/my.properties'

提醒一句 - 我希望在属性文件中成为布尔值的内容被视为字符串。

我试过了,下面的效果非常好:

test.properties
Monday=abcdef
Tuesday=kfgh

def props = readProperties  file:'/var/lib/jenkins/jobs/abc/test.properties'
def Var1= props['Monday']
def Var2= props['Tuesday']
echo "Var1=${Var1}"
echo "Var2=${Var2}"

我无法弄清楚如何从 readProperties 中插入纯文本,所以我只是做了一个扩展变量的解决方法。

def props = readProperties  file: 'dir/my.properties'
def release = expand_property(props['RELEASE'])

def expand_property(property) {
  def info 
  node("anyUnixNode") {
    info = sh(script: "echo $property", returnStdout: true)
  }
  info = info.trim()
  return info   
}

使用:

def props = readProperties file: 'config/general.properties'

如果您的属性文件位于 Groovy 库中,而源代码位于不同的位置,您应该使用 Groovy 库中的 Resources 文件夹。

因此添加下面一行:

--> def propFileContent = libraryResource 'config/general.properties'
    def props = readProperties text: propFileContent

备注:

  • "config" 是 'resources' 文件夹中的某个文件夹

  • 注意,第一处用了"file:",第二处用了"text:"