Create GIT tags from YAML pipeline

05 Oct 2022

It is a well-followed practice in software development to create tags based on the current state of your codebase when you do a production software release. So that, you can always come back to a tagged version and do hotfixes on top of that code. It allows the library or application maintainers to perform support fixes for the older product versions while working on new versions.

Creating GIT tags from Azure DevOps release pipelines is easy.

Classic Release Pipelines

For classic release pipelines, you can use the already available task to create the tags on the commit hash based on which you are releasing your application. It knows about the underlying repository details and commits hash to create tags on your behalf. It uses the Build Service Collection user's permission to make this change. 

Tag\Branch Git on Release - Visual Studio Marketplace

 YAML Pipeline

With the new YAML pipelines, your build and release are maintained in a similar fashion and under the "Pipelines" page. In most cases, the single YAML pipeline is enough to perform both build and staged releases. So, if you have a single pipeline for build & release then you can very well use the above GIT Tag on the release task. 

But when you have a requirement to break the build and release to multiple YAML pipelines, i.e., the artifact from a build should be used for more than one release flow or else there are multiple units with multiple release paths from the same build artifact then you would prefer to break the build & release into different YAML pipeline.

In the above-separated scenario, the release YAML pipeline will never have access to the GIT credential/session token resulting in a permission error while using the above "GIT Tag" task. I've contacted the task maintainer for the YAML pipeline support but he promptly responded and recommended that I should better use the GIT command line to create a tag.

So, based on the recommendation I was able to tag a particular GIT branch state using the following commands in the release YAML pipeline.

# Check out the code and keep the token so we can tag the repository
- checkout: self
  persistCredentials: true
  clean: true

# GIT tag from YAML pipeline
# Tag the current branch with the version number
- script: |
    git tag $(resources.pipeline.MyBuild.runName)
    git push origin $(resources.pipeline.MyBuild.runName)
  workingDirectory: $(Build.SourcesDirectory)
  displayName: Git Commit and Tag from pipeline
  continueOnError: true

Hope the above snippet helps you save some time.
Share your experience or suggest if you have an alternate way to do it in a simpler way ;)