From a14b2e78f43c691f189d3fe6e50b3b4534411cae Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Tue, 20 Jun 2017 11:24:02 +0200 Subject: [PATCH] Add `vault` template function Signed-off-by: Knut Ahlers --- README.md | 7 +++++ functions/func_vault.go | 61 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 functions/func_vault.go diff --git a/README.md b/README.md index 363bfc5..88c18d3 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,13 @@ # echo '{{now "2006-01-02 15:04:05"}}' | korvike 2017-04-17 16:27:34 ``` +- `{{ vault [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 + ``` ---- diff --git a/functions/func_vault.go b/functions/func_vault.go new file mode 100644 index 0000000..0712836 --- /dev/null +++ b/functions/func_vault.go @@ -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 "" +}