How to authenticate to Azure repositories and run Git commands in an Azure pipeline
When working with Azure Pipelines, you may encounter a situation where you don’t know the repository name before the pipeline runs. In such cases, using the checkout: git://MyProject/MyRepo
method won’t work, as variables can’t be used as values in that syntax.
You will get the following error from Git:
fatal: Cannot prompt because terminal prompts have been disabled.
fatal: could not read Password for 'https://[email protected]/...': terminal prompts disabled
To overcome this challenge, I came up with a solution: create a task at the beginning of your job definition that “authenticates” the pipeline against your Azure DevOps project.
Let’s see this in action.
If you try to use commands like git clone
directly, you’ll likely encounter the error: fatal: Cannot prompt because user interactivity has been disabled
This indicates that you first need to authenticate with your Azure DevOps project.
To authenticate, add the following PowerShell script as the first task in your job:
- pwsh:
git config --global http.extraheader "AUTHORIZATION: bearer $env:AZURE_DEVOPS_EXT_PAT"
env:
AZURE_DEVOPS_EXT_PAT: $(System.AccessToken)
Here are the key points to understand about this task:
- The
System.AccessToken
is a special variable that holds the security token used by the running build. You can find more information in the Microsoft documentation. - The AZURE_DEVOPS_EXT_PAT environment variable stores the Personal Access Token (PAT), which is then used in the PowerShell script.
- The
git config
command sets thehttp.extraheader
globally with your token, so you won’t need to specify it in subsequent Git commands.
Once authentication is complete, you can proceed with cloning a repository in a new task using the following command:
git clone https://dev.azure.com/{yourOrgName}/{yourProjectName}/_git/{yourRepoName}
.
For more authentication methods with Azure repositories, refer to this article from Microsoft.