github.com/Azure/aad-pod-identity@v1.8.17/test/image/identityvalidator/sp.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/Azure/go-autorest/autorest/adal"
     8  	"github.com/Azure/go-autorest/autorest/azure"
     9  	"k8s.io/klog/v2"
    10  )
    11  
    12  // assertWithSystemAssignedIdentity obtains a service principal token with system-assigned identity.
    13  func assertWithSystemAssignedIdentity() error {
    14  	spt, err := adal.NewServicePrincipalTokenFromManagedIdentity(azure.PublicCloud.ResourceManagerEndpoint, nil)
    15  	if err != nil {
    16  		return fmt.Errorf("failed to acquire a service principal token from IMDS, error: %+v", err)
    17  	}
    18  
    19  	ctx, cancel := context.WithTimeout(context.Background(), contextTimeout)
    20  	defer cancel()
    21  
    22  	if err := spt.RefreshWithContext(ctx); err != nil {
    23  		return fmt.Errorf("failed to refresh the service principal token, error: %+v", err)
    24  	}
    25  
    26  	token := spt.Token()
    27  	if token.IsZero() {
    28  		return fmt.Errorf("%+v is a zero token", token)
    29  	}
    30  
    31  	klog.Infof("successfully acquired a service principal token from IMDS")
    32  	return nil
    33  }