jenkinsfile - 如何访问我的 pom.xml 中的自定义属性?

Lor*_*HW4 6 groovy pom.xml maven jenkins

假设我的 pom.xml 中有一个自定义属性,如下所示:

<properties>
 <app>com.myProject.app</app>
</properties>
Run Code Online (Sandbox Code Playgroud)

如何在我的 jenkinsfile 中访问它?

这个:

def pom = readMavenPom file: 'pom.xml'
def appName = pom.app
Run Code Online (Sandbox Code Playgroud)

返回

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified field org.apache.maven.model.Model app
Run Code Online (Sandbox Code Playgroud)

提前致谢!

too*_*ger 6

我知道两种方法:

  1. 用于properties-maven-plugin将属性写入文件。readProperties在 Jenkinsfile 中使用以读取属性。
    仅当在 Maven 运行之后才需要属性时才有效。
    此外,在适当的情况下,属性文件可能是前一次运行中的陈旧文件,这很隐蔽,因为无论如何属性值在 99.9% 的时间都是正确的。
  2. 使用pom = readMavenPom 'path/to/pom.xml'. 事后,像这样访问属性:pom.properties['com.myProject.app']

我更喜欢方法 2:在 POM 中没有额外的插件配置,没有写入文件,更少的排序约束,更少的脆弱性。


小智 5

在管道风格中,在 Jenkinsfile 中您可以按如下方式访问该值

pipeline {

environment {
      POM_APP = readMavenPom().getProperties().getProperty('app')
}

stages{
    stage('app stage'){
        steps{
            script{
                 sh """
                 echo ${POM_APP}
                 """
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

读取maven项目文件