From ff4b3d763bfc1962c137c9740ce3a4131472aeb9 Mon Sep 17 00:00:00 2001 From: Kristin Laemmert Date: Wed, 6 Jun 2018 08:09:33 -0700 Subject: [PATCH] functions: fix lookup()'s handling of numberical defaults --- lang/funcs/collection.go | 14 ++++++++++---- lang/funcs/collection_test.go | 9 +++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/lang/funcs/collection.go b/lang/funcs/collection.go index 0fc898dfc..eddabfe7a 100644 --- a/lang/funcs/collection.go +++ b/lang/funcs/collection.go @@ -463,11 +463,11 @@ var LookupFunc = function.New(&function.Spec{ if len(args) < 1 || len(args) > 3 { return cty.NilVal, fmt.Errorf("lookup() takes two or three arguments, got %d", len(args)) } - var defaultVal string + var defaultVal cty.Value defaultValueSet := false if len(args) == 3 { - defaultVal = args[2].AsString() + defaultVal = args[2] defaultValueSet = true } @@ -489,10 +489,16 @@ var LookupFunc = function.New(&function.Spec{ } if defaultValueSet { - return cty.StringVal(defaultVal), nil + defaultType := defaultVal.Type() + switch { + case defaultType.Equals(cty.String): + return cty.StringVal(defaultVal.AsString()), nil + case defaultType.Equals(cty.Number): + return cty.NumberVal(defaultVal.AsBigFloat()), nil + } } - return cty.UnknownVal(cty.String), fmt.Errorf( + return cty.UnknownVal(cty.DynamicPseudoType), fmt.Errorf( "lookup failed to find '%s'", lookupKey) }, }) diff --git a/lang/funcs/collection_test.go b/lang/funcs/collection_test.go index 8d8e03783..eecff5ed6 100644 --- a/lang/funcs/collection_test.go +++ b/lang/funcs/collection_test.go @@ -1001,6 +1001,15 @@ func TestLookup(t *testing.T) { cty.StringVal("bar"), false, }, + { // Supplied default with valid (int) key + []cty.Value{ + simpleMap, + cty.StringVal("foo"), + cty.NumberIntVal(-1), + }, + cty.StringVal("bar"), + false, + }, { // Supplied default with invalid key []cty.Value{ simpleMap,