terraform-plugin-sdk
terraform-plugin-sdk copied to clipboard
GetOk output for null string field and empty string field are identical making it impossible to tell if a value is to be un-set or ignored.
Not sure if bug or feature but this has been kinda frustrating. I have an API that accepts a string field, and as far as requests go, it is valid to send a payload without the field, the field as an empty string (to unset the existing value) and of course the payload with a string.
Passing a zero value such as an empty string to un-set a field is impossible to handle due to the GetOk function returning identical responses for a field set to "" and a field set to null or omitted entirely.
Am I doing this wrong or is handling values that are zero values in Go unsupported?
Terraform Version
Terraform v0.14.4
Terraform Configuration Files
resource "dummy_resource" "test1" {
typeList_resource {
strField = ""
otherField = "stuff"
}
}
resource "dummy_resource" "test2" {
typeList_resource {
otherField = "stuff"
}
}
resource "dummy_resource" "test3" {
typeList_resource {
strField = "stuff"
otherField = "stuff"
}
}
...
Debug Output
Placing a logger on line 546 of resource_data.go inside the func (d *ResourceData) get(addr[]string, source, getSource) getResult {} method yields the following:
log.Println("Value:", result.Value, "zero_or_schema:" result.ValueOrZero(schema), "is nil?" result.Value == nil)
Value: <nil> zero_or_schema: is nil? true // test 1 - unexpected (expected is nil to be false and result.Value to be "")
Value: <nil> zero_or_schema: is nil? true // test 2 - expected (field omitted so should be nil)
Value: stuff zero_or_schema: stuff is nil? false. // test 3 - expected (field present and has non-empty value)
Also logging output of GetOk("typeList_resource.0.strField) yields
GetOK: false // test 1 - unexpected (expected true since this field is set, but to the zero value for string)
GetOK: false // test 2 - expected (field not set so should get false for second variable)
GetOK: stuff true. // test 3 - expected (field present and got true for second variable)
Crash Output
No Crash
Expected Behavior
Expected GetOk("typeList_resource.0.strField") to return "", true for the empty string and <nil> false for the missing field
Actual Behavior
GetOk("typeList_resource.0.strField") returns "", false in both cases. Now there's no way to tell which resource had the strField set to "" and which was missing entirely.
Steps to Reproduce
terraform initterraform apply
Additional Context
N/A
References
None
Another similar bug report, https://github.com/hashicorp/terraform-plugin-sdk/issues/962, contains a reproduction of this issue as well.
After running into this and exploring the ResourceData APIs to find a workaround, we found that using GetRawConfig() allows differentiating between a field being unset and the default value.
(e.g., for demonstration)
isFieldSet := d.GetRawConfig().AsValueMap()["field"].IsNull()