-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
92 lines (73 loc) · 2.11 KB
/
main.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
"github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/azure/auth"
)
func main() {
vaultName, ok := os.LookupEnv("KEYVAULT_VAULT_NAME")
if !ok {
log.Fatal("KEYVAULT_VAULT_NAME must be set.")
}
secretName, ok := os.LookupEnv("KEYVAULT_SECRET_NAME")
if !ok {
log.Fatal("KEYVAULT_SECRET_NAME must be set.")
}
clientID := os.Getenv("MSI_USER_ASSIGNED_CLIENTID")
keyClient, err := NewKeyVaultClient(vaultName, clientID)
if err != nil {
log.Fatal(err)
}
secret, err := keyClient.GetSecret(secretName)
if err != nil {
log.Fatal(err)
}
log.Printf("Retrieved secret '%s' from keyvault using MSI", secret)
}
// KeyVault holds the information for a keyvault instance
type KeyVault struct {
client *keyvault.BaseClient
vaultURL string
}
// NewKeyVaultClient creates a new keyvault client
func NewKeyVaultClient(vaultName, clientID string) (*KeyVault, error) {
// Change this to change auth method. Add new auth methods to change how
// auth is setup
authorizer, err := getMSIAuthorizer(clientID)
// authorizer, err := getAuthorizerFromEnv()
if err != nil {
return nil, err
}
keyClient := keyvault.New()
keyClient.Authorizer = authorizer
k := &KeyVault{
vaultURL: fmt.Sprintf("https://%s.%s", vaultName, azure.PublicCloud.KeyVaultDNSSuffix),
client: &keyClient,
}
return k, nil
}
func getMSIAuthorizer(clientID string) (autorest.Authorizer, error) {
msiKeyConfig := &auth.MSIConfig{
Resource: strings.TrimSuffix(azure.PublicCloud.KeyVaultEndpoint, "/"),
ClientID: clientID,
}
return msiKeyConfig.Authorizer()
}
func getAuthorizerFromEnv() (autorest.Authorizer, error) {
return auth.NewAuthorizerFromEnvironment()
}
// GetSecret retrieves a secret from keyvault
func (k *KeyVault) GetSecret(keyName string) (string, error) {
ctx := context.Background()
keyBundle, err := k.client.GetSecret(ctx, k.vaultURL, keyName, "")
if err != nil {
return "", err
}
return *keyBundle.Value, nil
}