How to clone Azure DevOps git repository with OAuth token from service principal?

299 Views Asked by At

I am trying to clone an Azure DevOps git repository using an Azure app registration/service principal.

I was successful in bash with the help of this answer.

Sadly, adapting it to GitPython results in an error:

GitCommandError: Cmd('git') failed with exit code 128:
    cmdline: git clone -v -- https://*****@dev.azure.com/example/repo/_git/repo /tmp/repo/
    Cloning into '/tmp/repo'...
fatal: could not read Password for 'https://<Access-Token>@dev.azure.com': No such device or address

Using a PAT worked with GitPython. But I do not want a user dependent way of accessing the Repository.

That's the code snippet trying to clone the repo:

# Azure AD authentication endpoint
tenant_id = "SomeTenantID"
auth_url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/token"


data = {
    "grant_type": "client_credentials",
    "client_id": "SomeClientID",
    "client_secret": "SomeSecret",
    "resource": "499b84ac-1321-427f-aa17-267ca6975798/.default"
}

response = requests.post(auth_url, data=data)
response_json = response.json()
access_token = response_json["access_token"]

repository_url = f"https://{access_token}@dev.azure.com/example/repo/_git/repo"
    
target_directory = "/tmp/repo/"

repo = git.Repo.clone_from(repository_url, target_directory)

Any ideas?

0

There are 0 best solutions below