[NoBrainer] Create git tag in a Azure DevOps YAML pipeline based on AssemblyVersion of a specific .csproj file

Let’s say you build and deploy your code using Azure DevOps services and want to create a git tag after each deployment to prod named after the assembly version in a specific .csproj file of your .NET solution. If your assembly version has the following format, the corresponding Azure DevOps pipeline job could look like the one shown below.

Version format: yyyy.MM.dd.revision (when using Semantic Versioning, just adjust the regexp accordingly)

<AssemblyVersion>2025.02.27.1</AssemblyVersion>
jobs:
  - job: CreateGitTag
    displayName: Create git tag
    steps:
      - checkout: self
        persistCredentials: true
        clean: true
      - task: PowerShell@2
        displayName: Get version number
        inputs:
          targetType: inline
          script: |
            $csprojFile = Get-ChildItem -Recurse Arbitrary.Project.csproj
            $rawAssemblyVersion = ([xml](Get-Content $csprojFile)).Project.PropertyGroup.AssemblyVersion
            $assemblyVersion = $rawAssemblyVersion -replace '(\d{4})\.(\d{2})\.(\d{2})\.(\d+)', '$1$2$3.$4'
            Write-Host("##vso[task.setvariable variable=VERSION]$assemblyVersion")
      - script: |
          git config --global user.name "AZURE_DEVOPS_PROJECT_NAME Build Service (AZURE_DEVOPS_ORG_NAME)"
          git config --global user.email "arbitrary@example.com"
          git tag -a $(VERSION) -m "Release $(VERSION)"
          git push origin $(VERSION)

After checking out the git repository, the job retrieves the version number from the AssemblyVersion tag of Arbitrary.Project.csproj (recursive search). The raw assembly version is then converted to the format yyyyMMdd.revision and stored in environment variable VERSION. In the last step a git tag with name equal to VERSION is created based on the currently checked out git branch. Last but not least, the tag gets pushed to the git repository. Do not forget to adjust the user.name and user.email based on your needs.

The job can be stored in a separate file (i.e. jobs-create-git-tag.yml) and can then be called as follows:

jobs:
  - template: jobs-create-git-tag.yml

IMPORTANT: To make the job working, the Azure DevOps specific build service user requires the following permissions.

  • Contribute
  • Create tag
  1. Go to Project settings
  2. Select Repositories in the menu on the left
  3. Click on the corresponding repository
  4. Navigate to tab Security
  5. Select PROJECT_NAME Build Service (ORGANIZATION_NAME)
  6. Allow the before listed permissions for the build service user

Leave a comment

Website Powered by WordPress.com.

Up ↑