Skip to content

Commit

Permalink
Add default Azure credential
Browse files Browse the repository at this point in the history
Since that's what we use locally.
  • Loading branch information
bcspragu committed Feb 14, 2024
1 parent 12721ac commit d7c8020
Showing 1 changed file with 18 additions and 9 deletions.
27 changes: 18 additions & 9 deletions azure/azcreds/azcreds.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,18 @@
package azcreds

import (
"errors"
"fmt"
"os"

"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)

// Type identifies the auth method we used to authenticate with Azure.
type Type string

const (
Default = Type("DEFAULT")
Environment = Type("ENVIRONMENT")
ManagedIdentity = Type("MANAGED_IDENTITY")
)
Expand All @@ -31,15 +32,15 @@ func New() (azcore.TokenCredential, Type, error) {
return newEnvCreds()
}

// We use "ManagedIdentity" instead of just "Default" because the default
// timeout is too low in azidentity.NewDefaultAzureCredentials, so it times out
// and fails to run.
azClientID := os.Getenv("AZURE_CLIENT_ID")
if azClientID == "" {
return nil, "", errors.New("no AZURE_CLIENT_SECERT or AZURE_CLIENT_ID found")
if azClientID := os.Getenv("AZURE_CLIENT_ID"); azClientID != "" {
// We use "ManagedIdentity" instead of just "Default" because the default
// timeout is too low in azidentity.NewDefaultAzureCredentials, so it times out
// and fails to run.
return newManagedIdentityCreds(azClientID)
}

return newManagedIdentityCreds(azClientID)
// Default to, well, the default, which will try all the various methods available.
return newDefaultCreds()
}

func newEnvCreds() (*azidentity.EnvironmentCredential, Type, error) {
Expand All @@ -56,7 +57,15 @@ func newManagedIdentityCreds(azClientID string) (*azidentity.ManagedIdentityCred
ID: azidentity.ClientID(azClientID),
})
if err != nil {
return nil, "", fmt.Errorf("failed to load Azure credentials: %w", err)
return nil, "", fmt.Errorf("failed to load managed identity Azure credentials: %w", err)
}
return creds, ManagedIdentity, nil
}

func newDefaultCreds() (*azidentity.DefaultAzureCredential, Type, error) {
creds, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
return nil, "", fmt.Errorf("failed to load default Azure credentials: %w", err)
}
return creds, Default, nil
}

0 comments on commit d7c8020

Please sign in to comment.