Using TypeSet in provider always adds an empty element on update

I’m writing a custom provider and am facing an issue with TypeSet.
Maybe it comes from a misunderstanding on my side but i can’t explain why it behaves this way.

I have a TypeSet in my schema with a resource element.
Whatever i do, when terraform calculates a plan and calls the resource update function, i always receive a set with items that are initialized with default values for the underlying schema.

For instance, i have 6 elements in the set and i want to keep only 1. Terraform first reads the resource to refresh the state, the read returns the 6 elements, then it calls update with a set containing 2 elements (the item coming from the config, plus another item with everything initialized with default value).

I would expect that update receives a set containing only 1 element.

Am i missing something ? Is it how a TypeSet should behave ?

1 Like

This doesn’t quite sound like normal behaviour, but we’ll need more info to understand what’s going on here. Could you link to the code in question, or post at least the schema, update function, and config?

You can look at the code here terraform-provider-kops/Resource_Cluster.generated.go at 604ba70740cf05d11e418e86d87125a5a1be18a7 · eddycharly/terraform-provider-kops · GitHub

I suspect it comes from the way sets behave, when sets contain optional and computed values, and the values are refreshed, the hash keys will never match with the config.

I don’t know if there is a solution for this. I didn’t find anything that allows refreshing a set entry before it is hashed and compared to existing items.

I have also experienced this issue. Everytime an item in a set is updated, terraform treats it as two separate items in a set (one is an empty item). Not sure how to resolve this. I tried using the Set function to force all items in the set to be treated as one (in my code there should only be one of this type) but terraform (proper cli) blew up on me.

1 Like

I am also experiencing this issue. I tried to convert this schema:

from TypeList to TypeSet, and our acceptance tests fail whenever we try to update the resource in-place because an additional null-valued entry appears in the set when the Update function is called, just as the other posters in this thread have reported.

Can anyone more familiar with Terraform internals shed light on why this is happening? Are there any workarounds other than leaving it as a list and writing extra code like diff suppress functions to ignore differences in order?

This has been reported already as an issue on Github and there’s even a proposed fix: Fix for TypeSet applying with unexpected empty element by prashantv · Pull Request #1042 · hashicorp/terraform-plugin-sdk · GitHub