I am currently setting up a robust CI/CD workflow and need to programmatically retrieve the project version from the pom.xml file during a Jenkins execution. While I am aware of the POM_VERSION variable in specific Maven job types, I am moving toward Declarative Pipelines. Is there a clean way to capture this version into an environment variable for tagging Docker images or managing releases without complex shell parsing?
3 answers
To handle this efficiently in a Declarative Pipeline, the most reliable method is using the 'Pipeline Utility Steps' plugin. You can use the readMavenPom step which parses the POM file into an object. For example, def pom = readMavenPom file: 'pom.xml' allows you to access pom.version directly. This approach is far superior to using grep or sed because it understands the XML structure and handles inheritance from parent poms correctly. Once captured, you can easily assign it to an environment variable or use it for dynamic Docker image tagging in your build stages.
Have you considered using the Maven Help Plugin instead of relying on extra Jenkins plugins? You can run a shell command like mvn help:evaluate -Dexpression=project.version -q -DforceStdout to print the version directly to the console and capture it. Does your current Jenkins environment allow for the installation of new plugins, or are you restricted to using standard shell executions within your pipeline stages?
If you are using the older "Maven Project" job type, Jenkins automatically provides the POM_VERSION environment variable. However, for Pipelines, the readMavenPom method mentioned above is the industry standard.
I agree with Amanda. Transitioning to Pipelines is essential for modern DevOps, and using the readMavenPom utility makes the Jenkinsfile much cleaner and easier for the team to maintain over time.
David, that is a great point for restricted environments. To answer your question, most enterprise setups prefer avoiding plugin bloat. You can capture that output in a script block like this: script { env.VERSION = sh(script: 'mvn help:evaluate...', returnStdout: true).trim() }. This ensures the version is available across all subsequent stages without needing the Utility Steps plugin.