jenkinsfile - How do I access custom properties in my pom.xml?

Viewed 10200

Let's say I have a custom property in my pom.xml set like this:

<properties>
 <app>com.myProject.app</app>
</properties>

How can I access it in my jenkinsfile?

This:

def pom = readMavenPom file: 'pom.xml'
def appName = pom.app

returns

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified field org.apache.maven.model.Model app

Thanks in advance!

4 Answers

I know two approaches:

  1. Use properties-maven-plugin to write the properties to a file. Use readProperties in the Jenkinsfile to read the properties.
    Works only if properties aren't needed until after Maven ran.
    Also, with the right circumstances, the properties file may be the stale one from a previous run, which is insiduous because the property values will be right anyway 99.9% of the time.
  2. Use pom = readMavenPom 'path/to/pom.xml'. Afterwards, access the property like this: pom.properties['com.myProject.app'].

I like approach 2 much better: No extra plugin configuration in the POM, no file written, less sequencing constraints, less fragilities.

In pipeline style, inside Jenkinsfile you can access the value as follows

pipeline {

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

stages{
    stage('app stage'){
        steps{
            script{
                 sh """
                 echo ${POM_APP}
                 """
            }
        }
    }
}

Read a maven project file

try this: IMAGE = readMavenPom().getArtifactId() VERSION = readMavenPom().getVersion()

jenkins pipeline add this stage. more see

    stage('info')
    {
        steps
        {
            script
            {
                def version = sh script: 'mvn help:evaluate -Dexpression=project.version -q -DforceStdout', returnStdout: true
                def artifactId = sh script: 'mvn help:evaluate -Dexpression=project.artifactId -q -DforceStdout', returnStdout: true
                
            }

        }
    }
Related