-
Notifications
You must be signed in to change notification settings - Fork 25
/
azure_msi.go
66 lines (56 loc) · 1.67 KB
/
azure_msi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
*/
package azure
import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/pkg/errors"
"k8s.io/client-go/util/retry"
"k8s.io/klog/v2"
"go.goms.io/fleet/pkg/interfaces"
)
const (
aksScope = "6dae42f8-4368-4678-94ff-3960e28e3630"
)
type azureAuthTokenProvider struct {
clientID string
}
func New(clientID string) interfaces.AuthTokenProvider {
return &azureAuthTokenProvider{
clientID: clientID,
}
}
// FetchToken gets a new token to make request to the associated fleet' hub cluster.
func (a *azureAuthTokenProvider) FetchToken(ctx context.Context) (interfaces.AuthToken, error) {
token := interfaces.AuthToken{}
opts := &azidentity.ManagedIdentityCredentialOptions{ID: azidentity.ClientID(a.clientID)}
klog.V(5).InfoS("FetchToken", "client ID", a.clientID)
credential, err := azidentity.NewManagedIdentityCredential(opts)
if err != nil {
return token, errors.Wrap(err, "failed to create managed identity cred")
}
var azToken *azcore.AccessToken
err = retry.OnError(retry.DefaultBackoff,
func(err error) bool {
return ctx.Err() == nil
}, func() error {
klog.V(5).InfoS("GetToken start", "credential", credential)
azToken, err = credential.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string{aksScope},
})
if err != nil {
klog.ErrorS(err, "Failed to GetToken")
}
return err
})
if err != nil {
return token, errors.Wrap(err, "failed to get a token")
}
token.Token = azToken.Token
token.ExpiresOn = azToken.ExpiresOn
return token, nil
}