How to get git branch at commit with tag at run Azure pipeline?



In Azure Pipeline is possible use predefined build variables (DevOps Services) Build.SourceBranch and Build.SourceBranchName but their values at case commit with tag are tags.

In doc. is written

  • When your pipeline is triggered by a tag: refs/tags/your-tag-name
  • The name of the branch in the triggering repo the build was queued for.
    Git repo branch or pull request: The last path segment in the ref. For example, in refs/heads/master this value is master. In refs/heads/feature/tools this value is tools.
  • this my observation: but in case commit with tag is the last path segment of Build.SourceBranch, so your-tag-name


As it is described in the document. If the pipeline is triggered by a tag. Then variables Build.SourceBranch and Build.SourceBranchName will be the tag name.

However, you can use git commands(git branch -r --contains $(Build.SourceBranchName) | grep -v $(Build.SourceVersion)) to retrieve the branch name that the tag points to.

If you want to use the branch name as variable, You can define a variable use the logging commands(echo "##vso[task.setvariable variable=CurrentBranch]$branch"). For below example:

- powershell: |
     #get the branch name
     $branch = git branch -r --contains $(Build.SourceBranchName) | grep -v $(Build.SourceVersion)
     #define varialbe CurrentBranch to hold the value.
     echo "##vso[task.setvariable variable=CurrentBranch]$branch" 

- powershell: echo "$(CurrentBranch)"  #use the branch name in the following steps by referring to $(CurrentBranch)

Answered By – Levi Lu-MSFT

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More