hashicorp / hashicorp/terraform-plugin-sdk

SetNew does not work on nested fields

Open
#459 5 comments 15 reactions 0 assignees View on GitHub
enhancement subsystem/types terraform-plugin-framework
Dominant language
Go
Stars
485
Forks
244
Avg merge
19h 57m
Merged PRs (30d)
4

Description

### SDK version
```
{
"Path": "github.com/hashicorp/terraform-plugin-sdk",
"Version": "v1.12.0"
}
```

### Use-cases
Currently, trying to set any nested (computed) field value in a `CustomizeDiff` function will fail due to a hardcoded `false` value on `d.checkKey()` in [`schema.ResourceDiff.SetNewComputed()`](https://github.com/hashicorp/terraform-plugin-sdk/blob/master/helper/schema/resource_diff.go#302) and [`schema.ResourceDiff.SetNew()`](https://github.com/hashicorp/terraform-plugin-sdk/blob/master/helper/schema/resource_diff.go#L290).

This seems to have been changed in commit [1e08e98](https://github.com/hashicorp/terraform-plugin-sdk/commit/1e08e982731eb0c0a35fc00dcc3878bb1f790f70#diff-5572654f34bded06e0d3e5eb9ed7d1bf). Not entirely sure why this change was made, and in any case, the Elasticsearch property is a list, but not a computed one, so not even that would be possible to Get and Set.

My use case is having global values in resources which are used to override nested values.

```go
func Deployment() *schema.Resource {
return &schema.Resource{
Schema: map[string]*schema.Schema{
"version": {
Type: schema.TypeString,
Required: true,
},

// Workloads
"elasticsearch": {
Type: schema.TypeList,
MinItems: 1,
MaxItems: 1,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// ...
"version": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
// ...
},
CustomizeDiff: customdiff.All(
customdiff.IfValueChange("version", func(old, new, meta interface{}) bool {
return new.(string) > old.(string)
}, func(d *schema.ResourceDiff, _ interface{}) error {
// Succeeds obtaining the key.
log.Println("[DEBUG]", d.Get("elasticsearch.0.version"))
// Fails setting ANY nested key.
if err := d.SetNew("elasticsearch.0.version", d.Get("elasticsearch.0.version")); err != nil {
return err
}
return nil
}),
),
}
}
```

### Proposal

Make `SetNewComputed` and `SetNew` able to set items on a list.

Contributor guide

Open the contributing guide

Research direction

Start in helper/schema/resource_diff.go at ResourceDiff.SetNewComputed(), ResourceDiff.SetNew(), and the d.checkKey() calls referenced by the issue. Review commit 1e08e98 and the nested list example, then verify that setting a nested list item succeeds without breaking existing key validation; the issue is done when both methods support the described nested use case.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.