-
Notifications
You must be signed in to change notification settings - Fork 309
/
azure.go
60 lines (49 loc) · 2 KB
/
azure.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
package util
import (
"fmt"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/go-logr/logr"
"sigs.k8s.io/yaml"
)
// AzureCreds is the file format we expect for credentials. It is copied from the installer
// to allow using the same credentials file for both:
// https://github.com/openshift/installer/blob/8fca1ade5b096d9b2cd312c4599881d099439288/pkg/asset/installconfig/azure/session.go#L36
type AzureCreds struct {
SubscriptionID string `json:"subscriptionId,omitempty"`
ClientID string `json:"clientId,omitempty"`
ClientSecret string `json:"clientSecret,omitempty"`
TenantID string `json:"tenantId,omitempty"`
}
// SetupAzureCredentials creates the Azure credentials needed to create Azure resources from credentials passed in from the user or from a credentials file
func SetupAzureCredentials(l logr.Logger, credentials *AzureCreds, credentialsFile string) (string, *azidentity.DefaultAzureCredential, error) {
creds := credentials
if creds == nil {
var err error
creds, err = ReadCredentials(credentialsFile)
if err != nil {
return "", nil, fmt.Errorf("failed to read the credentials: %w", err)
}
l.Info("Using credentials from file", "path", credentialsFile)
}
_ = os.Setenv("AZURE_TENANT_ID", creds.TenantID)
_ = os.Setenv("AZURE_CLIENT_ID", creds.ClientID)
_ = os.Setenv("AZURE_CLIENT_SECRET", creds.ClientSecret)
azureCreds, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
return "", nil, fmt.Errorf("failed to create Azure credentials to create image gallery: %w", err)
}
return creds.SubscriptionID, azureCreds, nil
}
// ReadCredentials reads a file with azure credentials and returns it as a struct
func ReadCredentials(path string) (*AzureCreds, error) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read from %s: %w", path, err)
}
var result AzureCreds
if err := yaml.Unmarshal(raw, &result); err != nil {
return nil, fmt.Errorf("failed to unmarshal credentials: %w", err)
}
return &result, nil
}