Search code examples
gitazure-devopsazure-active-directoryazure-service-principal

Azure Devops pipeline --> Git clone with service Principal


I previously was using a PAT token to authenticate with Azure DevOPS GIT in order to download submodules. Now I am trying to authenticate with a Service Principal since it is newly supported by Microsoft.

Given documentation and here, I came up with the following code which I should expect to work however the git clone step is not working correctly. The first half of the script seems to work because I am able to successfully retrieve a token. The error I am getting is fatal: could not read Password for 'https://[email protected]': terminal prompts disabled

 - task: Bash@3
  displayName: Fetch Submodules
  inputs:
    targetType: 'inline'
    script: |
      creds=$(curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "client_id=$client_id&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=$client_secret&grant_type=client_credentials" https://login.microsoftonline.com/$tenant_id/oauth2/v2.0/token)
      creds=$(echo "$creds" | jq -r .access_token)
      git -c http.https://dev.azure.com/conso/DevOps/_git/terraform.extraheader="AUTHORIZATION: Bearer $creds" submodule update --init --recursive
  env:
    client_id: xxx
    client_secret: "xxxx"
    tenant_id: xxx

The service principal has been added to Azure Devops User and has also been give read access to the repository I am cloning


Solution

  • So after a lot of trial and error, i've retweaked the bash script so that it looks something like this.

    The code below works within an Azure devops pipeline, can clone git repos and can also clone submodules.

              resource="499b84ac-1321-427f-aa17-267ca6975798"
    
              # Obtain the Azure AD authentication endpoint
              auth_url="https://login.microsoftonline.com/$tenant_id/oauth2/token"
    
              # Construct the data payload for the token request
              data="grant_type=client_credentials&client_id=$client_id&client_secret=$client_secret&resource=$resource"
    
              # Send a POST request to the authentication endpoint and capture the response
              access_token=$(curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "$data" "$auth_url" | jq -r .access_token)
    
              # Pull git repository
              git clone https://[email protected]/organisation/project/_git/myGitRepo myCustomFolder
    
              # Pull submodules
              git -c http.https://dev.azure.com/organisation/project/_git/myGitRepo.extraheader="AUTHORIZATION: Bearer $access_token" submodule update --init --recursive