Reputation: 1
I'm looking for a way to get Azure ACR access token using golang sdk. Similar to the result of the following console commands:
az login --service-principal -u <app-id> -p <password-or-cert> --tenant <tenant>
az acr login --name <registry id> --expose-token --only-show-errors
Upvotes: 0
Views: 1112
Reputation:
Here is my solution. Just set tenantId
and acrService
and run it. The output will give you user and password (token) to use in a docker login command. Please note: User is literally "00000000-0000-0000-0000-000000000000". Don't replace that.
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
func main() {
tenantId := "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
acrService := "crmichitest.azurecr.io"
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
panic(err)
}
ctx := context.Background()
aadToken, err := cred.GetToken(ctx, policy.TokenRequestOptions{Scopes: []string{"https://management.azure.com/.default"}})
if err != nil {
panic(err)
}
formData := url.Values{
"grant_type": {"access_token"},
"service": {acrService},
"tenant": {tenantId},
"access_token": {aadToken.Token},
}
jsonResponse, err := http.PostForm(fmt.Sprintf("https://%s/oauth2/exchange", acrService), formData)
if err != nil {
panic(err)
}
var response map[string]interface{}
json.NewDecoder(jsonResponse.Body).Decode(&response)
fmt.Println("User: 00000000-0000-0000-0000-000000000000")
fmt.Println("Token:", response["refresh_token"])
}
Then, just log into the registry:
docker login -u "00000000-0000-0000-0000-000000000000" -p "<TOKEN FROM OUTPUT>" crmichitest.azurecr.io
Upvotes: 1