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
93
94
95
96
97
98
99
100
101
102
103
|
package vault
import (
"fmt"
"os"
"github.com/hashicorp/vault/api"
"github.com/mitchellh/mapstructure"
)
type Credential struct {
Username string `json:"username"`
Password string `json:"password"`
}
type VaultKey struct {
Data Credential `json:"data"`
}
func loginAndRead(path string) (*api.Secret, error) {
c, err := api.NewClient(api.DefaultConfig())
if err != nil {
return nil, err
}
lc := c.Logical()
s, err := lc.Write("auth/approle/login", map[string]interface{}{
"role_id": os.Getenv("VAULT_ROLE_ID"),
"secret_id": os.Getenv("VAULT_SECRET_ID"),
})
if err != nil {
return nil, err
}
c.SetToken(s.Auth.ClientToken)
s, err = lc.Read(path)
if err != nil {
return nil, err
}
return s, nil
}
func GetVaultKeyStruct(path string, out interface{}) error {
s, err := loginAndRead(fmt.Sprintf("kv/data/%s", path))
if err != nil {
return err
}
if err = mapstructure.Decode(s.Data["data"], out); err != nil {
return err
}
return nil
}
// GetVaultApiKey fetches a JSON k/v value from Vault. The JSON document
// must have the format: { "key": "value" }
func GetVaultApiKey(path string) (string, error) {
s, err := loginAndRead(fmt.Sprintf("kv/data/%s", path))
if err != nil {
return "", err
}
ret := struct {
Key string `json:"key"`
}{}
if err = mapstructure.Decode(s.Data["data"], &ret); err != nil {
return "", err
}
return ret.Key, nil
}
// GetVaultKey fetches a JSON k/v value from vault. The JSON document
// must have the format:
// { "username": "username", "password": "password" }
func GetVaultKey(path string) (Credential, error) {
s, err := loginAndRead(fmt.Sprintf("kv/data/%s", path))
if err != nil {
return Credential{}, err
}
var vk VaultKey
if err = mapstructure.Decode(s.Data, &vk); err != nil {
return Credential{}, err
}
return vk.Data, nil
}
func GetVaultDatabase(path string) (Credential, error) {
s, err := loginAndRead(path)
if err != nil {
return Credential{}, err
}
return Credential{
Username: s.Data["username"].(string),
Password: s.Data["password"].(string),
}, nil
}
|