1
0
mirror of https://github.com/Luzifer/korvike.git synced 2024-09-19 00:42:57 +00:00

Add vault template function

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2017-06-20 11:24:02 +02:00
parent 4451301ea1
commit a14b2e78f4
Signed by: luzifer
GPG Key ID: DC2729FDD34BE99E
2 changed files with 68 additions and 0 deletions

View File

@ -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
View 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 ""
}