From ee0ea1e82e53c34508c077e914102061b24ec6f5 Mon Sep 17 00:00:00 2001
From: Knut Ahlers <knut@ahlers.me>
Date: Mon, 11 Jul 2016 17:22:05 +0200
Subject: [PATCH] allow templating in input file

---
 main.go | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)

diff --git a/main.go b/main.go
index ffce69a..d8dc1a1 100644
--- a/main.go
+++ b/main.go
@@ -1,7 +1,9 @@
 package main
 
 import (
+	"bytes"
 	"fmt"
+	"html/template"
 	"io/ioutil"
 	"log"
 	"os"
@@ -172,6 +174,11 @@ func importToVault(client *api.Client) error {
 		return err
 	}
 
+	keysRaw, err = parseImportFile(keysRaw)
+	if err != nil {
+		return err
+	}
+
 	var keys importFile
 	if err := yaml.Unmarshal(keysRaw, &keys); err != nil {
 		return err
@@ -186,3 +193,26 @@ func importToVault(client *api.Client) error {
 
 	return nil
 }
+
+func parseImportFile(in []byte) (out []byte, err error) {
+	funcMap := template.FuncMap{
+		"env": func(name string, v ...string) string {
+			defaultValue := ""
+			if len(v) > 0 {
+				defaultValue = v[0]
+			}
+			if value, ok := os.LookupEnv(name); ok {
+				return value
+			}
+			return defaultValue
+		},
+	}
+
+	t, err := template.New("input file").Funcs(funcMap).Parse(string(in))
+	if err != nil {
+		return nil, err
+	}
+
+	buf := bytes.NewBuffer([]byte{})
+	return buf.Bytes(), t.Execute(buf, nil)
+}