mavenjenkinsjenkins-declarative-pipeline

incrementing maven version through jenkins declarative pipeline


I'm trying to increment my pom version through Jenkins, but am facing many issues with the script element of the Jenkins declarative pipeline. My goal is:

  1. Jenkins pulls code from SCM
  2. Run maven plugins
  3. Increment version of application in the pom
  4. Merge the new pom back into the SCM

I've managed to remove '-SNAPSHOT' from the version, and I've stored the version (e.g 1.0.0) in a variable within the script element of the pipeline. I am unable to then use that variable to be able tin increment it.

pipeline {
    agent any
    tools { 
        maven 'maven'
    }
    stages {
        stage ('Git checkout branch') {
            steps {
                git branch: 'branch', credentialsId: '****', url: 'https://projectRepo'
            }
        }
        stage ('Increment snapshot') {
            steps {
                dir('directory') {
                    //Remove snapshot from version in pom
                    sh 'mvn versions:set -DremoveSnapshot'
                    script {
                        //Get the version and assign to variable 'version'
                        version = '$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout)'
                    }
                    //content of version can only be accessed by ${version}
                    sh "echo ${version}"
                }
            }
        }
    }
}

My aim is to get the version within the script tags, then perform a split like this .split("\."), then increment the last number, then, when I do a release, I'll use the maven flag to update the pom with the new version, plus add -SNAPSHOT to the end of the version


Solution

  • When you use the build-helper-maven-plugin, you can parse the version into its components:

    https://www.mojohaus.org/build-helper-maven-plugin/parse-version-mojo.html

    This offers not only elements like majorVersion and minorVersion, but also nextMajorVersion, nextMinorVersion etc.