How to get Git Tag in Azure Pipelines

The other answers here cover the first part of the question, so as Alex Kaszynski has already pointed out, you can use a YAML condition:

startsWith(variables['Build.SourceBranch'], 'refs/tags/')

Getting the tag name is now a bit easier than it was at the time the question was asked:

Build.SourceBranchName

This variable contains the last git ref path segment, so for example if the tag was refs/tags/1.0.2, this variable will contain 1.0.2: the tag name.

Full docs are now here.


git describe can provide you with the (closest) tag name for a given git hash and Azure can give you the current hash with $(Build.SourceVersion).

Use the --exact-match to limit git describe to only use a tag from the specific commit:

git describe --exact-match $(Build.SourceVersion)

If there is a tag, it'll be returned on stdout:

$ git describe --exact-match d9df242
v1.0.0

If there is no tag, git describe --exact-match exits with exit code 128:

$ git describe --exact-match cc1f9d2
fatal: no tag exactly matches 'cc1f9d23854c37dec000485c6c4009634516a148'
$ echo $?
128

so you can use this in a test or simply fail the task in pipelines that trigger on more than just tagged revisions.


To check if the commit was from a tag, use:

startsWith(variables['Build.SourceBranch'], 'refs/tags/')

From James Thurley:

Get the name of the tag with:

$tags = git tag --sort=-creatordate
$tag = $tags[0]

This sorts the tags correctly for both annotated and unannotated tags, and so the first result is the most recent tag.

I've removed the original answer and replaced it with the correct one from James Thurley. I'd delete my answer, but it appears you can't delete an accepted answer.


The accepted answer using git tag -l v* didn't work for me as it didn't order the tags correctly, instead giving 1.1, 1.11, 1.12, 1.2, 1.3, etc.

I found it better to do:

$tags = git tag --sort=-creatordate
$tag = $tags[0]

This sorts the tags correctly for both annotated and unannotated tags, and so the first result is the most recent tag.