'Get the branch that triggered the pipeline in azure pipelines

I've an azure yaml based pipeline that has a CI trigger with a branch pattern filter. How can I get the name of the branch that has triggered the pipeline?

Pipeline looks like this -

parameters:
- name: TargetBranch
  displayName: Target Branch
  type: string
  default: main


resources:
  repositories:
  - repository: <reponame>
    type: git
    name: <reponname>
    ref: refs/heads/main

trigger:
  branches:
    include:
    - es/branchtype1/*

pool: 
<rest of the yml here that requires the branch name that triggered the pipeline>

There can be many branches with es/branchtype1/* name(created on daily basis). Whenever there
is a push to any of these branches, this pipeline gets triggered. I need to get the name of the branch on which the push was made.



Solution 1:[1]

You can use the Build variable Build.SourceBranch.

The branch of the triggering repo the build was queued for. Some examples:

  • Git repo branch: refs/heads/master
  • Git repo pull request: refs/pull/1/merge
  • TFVC repo branch: $/teamproject/main
  • TFVC repo gated check-in: Gated_2016-06-06_05.20.51.4369;[email protected]
  • TFVC repo shelveset build: myshelveset;[email protected]
  • When your pipeline is triggered by a tag: refs/tags/your-tag-name

When you use this variable in your build number format, the forward slash characters (/) are replaced with underscore characters (_).

Note: In TFVC, if you are running a gated check-in build or manually building a shelveset, you cannot use this variable in your build number format.

More information: Use predefined variables - Build variables (DevOps Services)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rickvdbosch