From 80385c7682c5bb30ea4207dd4dedaf0eab1feb58 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Tue, 22 Jul 2014 18:35:36 -0700 Subject: [PATCH] config: add file() function for reading file contents --- config/interpolate_funcs.go | 19 +++++++++++++ config/interpolate_funcs_test.go | 49 ++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/config/interpolate_funcs.go b/config/interpolate_funcs.go index 9c076db2d..ef0d06ee6 100644 --- a/config/interpolate_funcs.go +++ b/config/interpolate_funcs.go @@ -2,6 +2,7 @@ package config import ( "fmt" + "io/ioutil" "strings" ) @@ -10,10 +11,28 @@ var Funcs map[string]InterpolationFunc func init() { Funcs = map[string]InterpolationFunc{ + "file": interpolationFuncFile, "lookup": interpolationFuncLookup, } } +// interpolationFuncFile implements the "file" function that allows +// loading contents from a file. +func interpolationFuncFile( + vs map[string]string, args ...string) (string, error) { + if len(args) != 1 { + return "", fmt.Errorf( + "file expects 1 arguments, got %d", len(args)) + } + + data, err := ioutil.ReadFile(args[0]) + if err != nil { + return "", err + } + + return string(data), nil +} + // interpolationFuncLookup implements the "lookup" function that allows // dynamic lookups of map types within a Terraform configuration. func interpolationFuncLookup( diff --git a/config/interpolate_funcs_test.go b/config/interpolate_funcs_test.go index 20f964c43..9b008b8cb 100644 --- a/config/interpolate_funcs_test.go +++ b/config/interpolate_funcs_test.go @@ -1,9 +1,58 @@ package config import ( + "io/ioutil" + "os" "testing" ) +func TestInterpolateFuncFile(t *testing.T) { + tf, err := ioutil.TempFile("", "tf") + if err != nil { + t.Fatalf("err: %s", err) + } + path := tf.Name() + tf.Write([]byte("foo")) + tf.Close() + defer os.Remove(path) + + cases := []struct { + Args []string + Result string + Error bool + }{ + { + []string{path}, + "foo", + false, + }, + + // Invalid path + { + []string{"/i/dont/exist"}, + "", + true, + }, + + // Too many args + { + []string{"foo", "bar"}, + "", + true, + }, + } + + for i, tc := range cases { + actual, err := interpolationFuncFile(nil, tc.Args...) + if (err != nil) != tc.Error { + t.Fatalf("%d: err: %s", i, err) + } + + if actual != tc.Result { + t.Fatalf("%d: bad: %#v", i, actual) + } + } +} func TestInterpolateFuncLookup(t *testing.T) { cases := []struct { M map[string]string