diff --git a/.changes/v1.12/BUG FIXES-20250310-093153.yaml b/.changes/v1.12/BUG FIXES-20250310-093153.yaml new file mode 100644 index 000000000000..de9f86c6a3ac --- /dev/null +++ b/.changes/v1.12/BUG FIXES-20250310-093153.yaml @@ -0,0 +1,5 @@ +kind: BUG FIXES +body: Return error when the templatestring function contains only a single interpolation that evaluates to a null value +time: 2025-03-10T09:31:53.479704+01:00 +custom: + Issue: "36652" diff --git a/internal/lang/funcs/string.go b/internal/lang/funcs/string.go index c026bb9508ca..932c36da774f 100644 --- a/internal/lang/funcs/string.go +++ b/internal/lang/funcs/string.go @@ -380,6 +380,14 @@ func makeRenderTemplateFunc(funcsCb func() (funcs map[string]function.Function, if diags.HasErrors() { return cty.DynamicVal, diags } + if val.IsNull() { + return cty.DynamicVal, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Template result is null", + Detail: "The result of the template is null, which is not a valid result for a templatestring call.", + Subject: expr.Range().Ptr(), + } + } return val, nil } } diff --git a/internal/lang/funcs/string_test.go b/internal/lang/funcs/string_test.go index 19f2f7f13823..83b602aa1583 100644 --- a/internal/lang/funcs/string_test.go +++ b/internal/lang/funcs/string_test.go @@ -273,6 +273,28 @@ func TestTemplateString(t *testing.T) { want cty.Value wantErr string }{ + { // a single string interpolation that evaluates to null should fail + `template`, + map[string]cty.Value{ + "template": cty.StringVal(`${test}`), + }, + cty.ObjectVal(map[string]cty.Value{ + "test": cty.NullVal(cty.String), + }), + cty.NilVal, + `:1,1-8: Template result is null; The result of the template is null, which is not a valid result for a templatestring call.`, + }, + { // a single string interpolation that evaluates to unknown should not fail + `template`, + map[string]cty.Value{ + "template": cty.StringVal(`${test}`), + }, + cty.ObjectVal(map[string]cty.Value{ + "test": cty.UnknownVal(cty.String), + }), + cty.UnknownVal(cty.String).RefineNotNull(), + ``, + }, { `template`, map[string]cty.Value{