From 5b915f2ec6018205581900f87a8efee43ee289eb Mon Sep 17 00:00:00 2001 From: Rudo Thomas Date: Thu, 24 Mar 2022 21:33:17 +0100 Subject: [PATCH] helper/schema: Allow Schema with TypeInt to accept string values from DefaultFunc(). (#841) This brings the int field up to par with bool and float ones. Fixes https://github.com/hashicorp/terraform-plugin-sdk/issues/773 --- helper/schema/schema.go | 13 ++++++++++++- helper/schema/schema_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/helper/schema/schema.go b/helper/schema/schema.go index d2da29ac469..fdd080a9737 100644 --- a/helper/schema/schema.go +++ b/helper/schema/schema.go @@ -2245,8 +2245,19 @@ func (m schemaMap) validatePrimitive( // decode a float as an integer. // the config shims only use int for integral number values + // also accept a string, just as the TypeBool and TypeFloat cases do if v, ok := raw.(int); ok { decoded = v + } else if _, ok := raw.(string); ok { + var n int + if err := mapstructure.WeakDecode(raw, &n); err != nil { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: err.Error(), + AttributePath: path, + }) + } + decoded = n } else { return append(diags, diag.Diagnostic{ Severity: diag.Error, @@ -2255,7 +2266,7 @@ func (m schemaMap) validatePrimitive( }) } case TypeFloat: - // Verify that we can parse this as an int + // Verify that we can parse this as a float var n float64 if err := mapstructure.WeakDecode(raw, &n); err != nil { return append(diags, diag.Diagnostic{ diff --git a/helper/schema/schema_test.go b/helper/schema/schema_test.go index 890c8d75a60..d1e29fff81d 100644 --- a/helper/schema/schema_test.go +++ b/helper/schema/schema_test.go @@ -6744,6 +6744,33 @@ func TestSchemaMap_Validate(t *testing.T) { }, Err: true, }, + "bool with DefaultFunc that returns str": { + Schema: map[string]*Schema{ + "bool_field": { + Type: TypeBool, + Optional: true, + DefaultFunc: func() (interface{}, error) { return "true", nil }, + }, + }, + }, + "float with DefaultFunc that returns str": { + Schema: map[string]*Schema{ + "float_field": { + Type: TypeFloat, + Optional: true, + DefaultFunc: func() (interface{}, error) { return "1.23", nil }, + }, + }, + }, + "int with DefaultFunc that returns str": { + Schema: map[string]*Schema{ + "int_field": { + Type: TypeInt, + Optional: true, + DefaultFunc: func() (interface{}, error) { return "1", nil }, + }, + }, + }, } for tn, tc := range cases {