I'm looking for a solution to dynamically select a branch to build in the Azure pipeline. I have Azure Repos Git where I select project, repository and default branch. I would like to be able to select branch based on a variable.
What I'm trying now is to use the Command Line task and fire a git checkout command (e.g. branch is a variable):
git checkout $(branch)
I can't confirm it working yet but still I confirm it works but I feel that there is a better option than checking out default branch and then switching branch with the command line.
Update:
If you want to have single pipeline that can build different branches (version branches) for different branches, you could just specify them in the trigger of branch filters. This will not build all branches.
The branch you select in build definition is just the default branch used when you Queue New Build manually. OTOH the build trigger establish which branch to download, e.g. if the build has been triggered by a git push on branch develop then that is the one checkout'ed and built. Take a look at this link: Get the sources from the branch that triggered the build in Team Services
Besides, you could disable the default get source step.Then use you own powershell script and git command to get source code manually(just what you want) and check out branch, finally build based on your variable.
For YAML, to disable the default "Get Sources" just specify none in the checkout:
checkout: none
For UI, please refer my reply in this question: Is it able to ignore/disable the first step Get source in vNext Build?
Assuming you're choosing the default branch. That doesn't mean that it's the only branch that can be built by that build definition.
You can choose which branches to monitor for CI (on the Triggers tab, you can add multiple branch filters to represent the branches you wish to build on commit), and the appropriate branch will be checked out when the build is triggered. You can also choose an alternate branch when manually queuing the build.
Source Link: Get Sources from multiple branches
If you want to dynamically select default branch as below, this is not available at present.

This is the branch that you want to be the default when you manually queue this build. If you set a scheduled trigger for the build, this is the branch from which your build will get the latest sources.
The default branch has no bearing when the build is triggered through continuous integration (CI). Usually you'll set this to be the same as the default branch of the repository (for example, "master").
There is a related user voice here: When triggering a build, use the same branch as the trigger build. You could kindly vote up and track the process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With