List all Azure container registry images via Golang

Viewed 71

I would like to list all images from Azure registry via Golang.

What I founded is this: https://github.com/Azure-Samples/azure-sdk-for-go-samples/tree/main/sdk/resourcemanager/containerregistry but nothing from there seems to help me.

Any ideas please?

LE: I ended up with this code

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "net/url"

    "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    "github.com/Azure/azure-sdk-for-go/services/preview/containerregistry/runtime/2019-08-15-preview/containerregistry"
    "github.com/Azure/go-autorest/autorest"
)

type ACRTokenProvider struct {
    accessToken string
}

func (a *ACRTokenProvider) OAuthToken() string {
    return a.accessToken
}

func newACRAuthorizer() (*autorest.BearerAuthorizer, error) {
    tenantId := "TENANT_ID"
    acrService := "servicename.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/"}})
    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)

    return autorest.NewBearerAuthorizer(&ACRTokenProvider{accessToken: fmt.Sprint(response["refresh_token"])}), nil
}

func main() {
    client := containerregistry.NewRepositoryClient("https://servicename.azurecr.io")
    authorizer, err := newACRAuthorizer()
    if err != nil {
        fmt.Println(err)
    }
    client.Authorizer = authorizer

    // Do what you need to do with client here
    attributes, err := client.GetList(context.Background(), "registryName", nil)
    if err != nil {
        log.Printf("Error while fetching attributes, %v ", err)
    }
    fmt.Print(attributes)
}

But the response is this

Original Error: autorest/azure: Service returned an error. Status=401 Code="Unknown" Message="Unknown service error" Details=[{"errors":[{"code":"UNAUTHORIZED","detail":[{"Action":"*","Name":"catalog","Type":"registry"}],"message":"authentication required, visit https://aka.ms/acr/authorization for more information."}]}]

What I'm missing?

1 Answers
Related