mirror of
https://github.com/Luzifer/korvike.git
synced 2024-11-08 15:30:05 +00:00
Add vault
template function
Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
parent
4451301ea1
commit
a14b2e78f4
2 changed files with 68 additions and 0 deletions
|
@ -33,6 +33,13 @@
|
|||
# echo '{{now "2006-01-02 15:04:05"}}' | korvike
|
||||
2017-04-17 16:27:34
|
||||
```
|
||||
- `{{ vault <path> <key> [default value] }}`
|
||||
Read a key from Vault using `VAULT_ADDR` and `VAULT_TOKEN` environment variables (or `~/.vault-token` file) for authentication.
|
||||
```bash
|
||||
# vault write secret/test foo=bar
|
||||
# echo '{{vault "secret/test" "foo"}}' | korvike
|
||||
bar
|
||||
```
|
||||
|
||||
----
|
||||
|
||||
|
|
61
functions/func_vault.go
Normal file
61
functions/func_vault.go
Normal file
|
@ -0,0 +1,61 @@
|
|||
package functions
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"github.com/hashicorp/vault/api"
|
||||
homedir "github.com/mitchellh/go-homedir"
|
||||
)
|
||||
|
||||
func init() {
|
||||
registerFunction("vault", func(name string, v ...string) (interface{}, error) {
|
||||
if name == "" {
|
||||
return nil, fmt.Errorf("Path is not set")
|
||||
}
|
||||
if len(v) < 1 {
|
||||
return nil, fmt.Errorf("Key is not set")
|
||||
}
|
||||
|
||||
client, err := api.NewClient(&api.Config{
|
||||
Address: os.Getenv(api.EnvVaultAddress),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client.SetToken(vaultTokenFromEnvOrFile())
|
||||
|
||||
secret, err := client.Logical().Read(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if secret != nil && secret.Data != nil {
|
||||
if val, ok := secret.Data[v[0]]; ok {
|
||||
return val, nil
|
||||
}
|
||||
}
|
||||
|
||||
if len(v) < 2 {
|
||||
return nil, fmt.Errorf("Requested value %q in key %q was not found in Vault and no default was set", v[0], name)
|
||||
}
|
||||
|
||||
return v[1], nil
|
||||
})
|
||||
}
|
||||
|
||||
func vaultTokenFromEnvOrFile() string {
|
||||
if token := os.Getenv(api.EnvVaultToken); token != "" {
|
||||
return token
|
||||
}
|
||||
|
||||
if f, err := homedir.Expand("~/.vault-token"); err == nil {
|
||||
if b, err := ioutil.ReadFile(f); err == nil {
|
||||
return string(b)
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
Loading…
Reference in a new issue