Search code examples
mavenazure-pipelinespom.xml

How to update version in POM file on branch after build number is incremented in Azure Pipeline


I am new to both Azure Pipelines as well as Maven. I have this pipeline setup that changes the version number in the POM file and then executes a maven clean install:

Trigger:
- none

pool:
   name: Azure Build VM
   demands:
   - Cmd

name: $(BuildVersion)$(Rev:.r)

steps:
- task: MavenAuthenticate@0
  inputs:
    artifactsFeeds: 'InternalRepo'

- script: |
    cd JavaRESTfulEngine
    mvn versions:set -DnewVersion=$(Build.BuildNumber)
  displayName: 'Change POM Version'

- script: |
    cd JavaRESTfulEngine
    mvn clean install
    rename C:\Users\Build\.m2\repository\net\windward\JavaRESTfulEngine\$(Build.BuildNumber)\JavaRESTfulEngine-$(Build.BuildNumber).war ROOT.war
    mkdir C:\Users\Build\.m2\repository\net\windward\JavaRESTfulEngine\$(Build.BuildNumber)\App_Data
    mkdir C:\Users\Build\.m2\repository\net\windward\JavaRESTfulEngine\$(Build.BuildNumber)\App_Data\requests
    rename C:\Users\Build\.m2\repository\net\windward\JavaRESTfulEngine\$(Build.BuildNumber)\JavaRESTfulEngine-$(Build.BuildNumber).war ROOT.war
    del C:\Users\Build\.m2\repository\net\windward\JavaRESTfulEngine\$(Build.BuildNumber)\_remote.repositories 
  displayName: 'Build with Maven'

This works, and the artifact has the right version number. My question is can I then proceed to update the version in the POM on the master branch to match $(Build.BuildNumber) such that the next time I pull from master I have the same version as the latest build? What would be the best way to do this?


Solution

  • If you want to update the version in the POM to match $(Build.BuildNumber), you could try following steps.

    My pom.xml is under the root directory, and I want to update the modelVersion. enter image description here

    # Specify the file path
    $xmlFileName= "pom.xml"
    # Read the existing file
    [xml]$xmlDoc = Get-Content $xmlFileName
    # If it was one specific element you can just do like so:
    $xmlDoc.project.modelVersion = "$(Build.BuildNumber)"
    #Remove the old pom.xml
    Remove-Item $xmlFileName
    # Then you can save that back to the xml file
    $xmlDoc.Save("$(System.DefaultWorkingDirectory)\pom.xml")
    # Print new file content
    gc $(System.DefaultWorkingDirectory)\pom.xml
    

    See this thread: Powershell script to update XML file content for more details.