Setting Git Tag from Azure Devops Build Pipeline on Complete

Brett picture Brett · Dec 7, 2019 · Viewed 12.9k times · Source

I'm trying to set a tag with the current version number determined by GitVersion on the GIT commit at the end of a successful build. Feels like I can't be the first one to be doing this, but I'm struggling to find something that works.

Azure Devops Pipeline has a feature in Get Sources to "Tag sources" On Success. I've set this and set to a variable that is set by one of the Agent Tasks I have (GitVersion)

Tag Sources

I can see in the debug logs that this variable is getting set by the GitVersion component that I've added to the pipeline.

2019-12-06T20:54:20.2390794Z ##[debug]Processed: ##vso[task.setvariable variable=GitVersion.MajorMinorPatch;]2.98.0

However if I leave it just as this, I get a tag created as "v$(GitVersion.MajorMinorPatch)" which means that at the time that the tag is being created that that variable no longer exists.

The Tag Format help tooltip says

"Tag format could be a combination of user-defined or pre-defined variables that have a scope of "All". For example: '$(Build.DefinitionName)$(Build.DefinitionVersion)$(Build.BuildId)$(Build.BuildNumber)$(My.Variable)'"

So I guess the problem is that this variable created during the pipeline does not have a scope of All.

I then tried adding a pipeline variable to the pipeline of "GitVersion.MajorMinorPatch" with the hope that this was at the right scope and hoping that when the "task.setvariable" command is run, that this will set the variable value of this higher scoped variable.

enter image description here

However in this case I just got a tag "v" created.

So I am a bit stuck. Somehow I need to be able to dynamically create or set a variable at scope ALL with the value I want to tag here.

I'd be really grateful for any ideas on this.

Answer

Paul Hatcher picture Paul Hatcher · Mar 21, 2020

If you are doing a yaml pipeline, you can add the following steps

- checkout: self
  persistCredentials: true

## Rest of pipeline ##

- script: |
     git tag $(GitVersion.NugetVersionV2)
     git push origin $(GitVersion.NugetVersionV2)
  workingDirectory: $(Build.SourcesDirectory)

The persistCredentials allows the token to be automatically passed to other git commands. Note the assignment of workingDirectory, otherwise I had an error that the location was not a git repository.

For an annotated tag rather than lightweight tag, the syntax would look like this...

- script: |
     git tag -a <tagname> -m <message>

To get a user/date against it you need to set the user name/email as well e.g.

- script: |
    git config --global user.name "BuildService"
    git config --global user.email "[email protected]"
    git tag -a <tagname> -m <message>

For this to work, the Project Collection Build Server account (not the Project Build Service Accounts group) needs to be allocated the Contribute permission for the Repositories