diff --git a/config/interpolate_funcs.go b/config/interpolate_funcs.go index c7bcafc70..4dd257a8c 100644 --- a/config/interpolate_funcs.go +++ b/config/interpolate_funcs.go @@ -79,6 +79,7 @@ func Funcs() map[string]ast.Function { "md5": interpolationFuncMd5(), "merge": interpolationFuncMerge(), "min": interpolationFuncMin(), + "pathexpand": interpolationFuncPathExpand(), "uuid": interpolationFuncUUID(), "replace": interpolationFuncReplace(), "sha1": interpolationFuncSha1(), @@ -431,6 +432,17 @@ func interpolationFuncMin() ast.Function { } } +// interpolationFuncPathExpand will expand any `~`'s found with the full file path +func interpolationFuncPathExpand() ast.Function { + return ast.Function{ + ArgTypes: []ast.Type{ast.TypeString}, + ReturnType: ast.TypeString, + Callback: func(args []interface{}) (interface{}, error) { + return homedir.Expand(args[0].(string)) + }, + } +} + // interpolationFuncCeil returns the the least integer value greater than or equal to the argument func interpolationFuncCeil() ast.Function { return ast.Function{ diff --git a/config/interpolate_funcs_test.go b/config/interpolate_funcs_test.go index a6b7757d5..0efd6f2fe 100644 --- a/config/interpolate_funcs_test.go +++ b/config/interpolate_funcs_test.go @@ -8,8 +8,11 @@ import ( "testing" "time" + "path/filepath" + "github.com/hashicorp/hil" "github.com/hashicorp/hil/ast" + "github.com/mitchellh/go-homedir" ) func TestInterpolateFuncZipMap(t *testing.T) { @@ -1972,3 +1975,39 @@ func testFunction(t *testing.T, config testFunctionConfig) { } } } + +func TestInterpolateFuncPathExpand(t *testing.T) { + homePath, err := homedir.Dir() + if err != nil { + t.Fatalf("Error getting home directory: %v", err) + } + testFunction(t, testFunctionConfig{ + Cases: []testFunctionCase{ + { + `${pathexpand("~/test-file")}`, + filepath.Join(homePath, "test-file"), + false, + }, + { + `${pathexpand("~/another/test/file")}`, + filepath.Join(homePath, "another/test/file"), + false, + }, + { + `${pathexpand("/root/file")}`, + "/root/file", + false, + }, + { + `${pathexpand("/")}`, + "/", + false, + }, + { + `${pathexpand()}`, + nil, + true, + }, + }, + }) +} diff --git a/website/source/docs/configuration/interpolation.html.md b/website/source/docs/configuration/interpolation.html.md index c3f98c6b1..5c2f58d61 100644 --- a/website/source/docs/configuration/interpolation.html.md +++ b/website/source/docs/configuration/interpolation.html.md @@ -271,6 +271,8 @@ The supported built-in functions are: * `md5(string)` - Returns a (conventional) hexadecimal representation of the MD5 hash of the given string. + * `pathexpand(string)` - Returns a filepath string with `~` expanded to the home directory. + * `replace(string, search, replace)` - Does a search and replace on the given string. All instances of `search` are replaced with the value of `replace`. If `search` is wrapped in forward slashes, it is treated