Skip to content

Commit 0cdd87d

Browse files
authored
add SetAttribute method on tfsdk rsource and add tests (#1205)
1 parent e08a7f1 commit 0cdd87d

File tree

2 files changed

+516
-0
lines changed

2 files changed

+516
-0
lines changed

tfsdk/resource.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,40 @@ func (r *Resource) Set(ctx context.Context, val interface{}) diag.Diagnostics {
6060
return diags
6161
}
6262

63+
// SetAttribute sets the attribute at `path` using the supplied Go value.
64+
//
65+
// The attribute path and value must be valid with the current schema. If the
66+
// attribute path already has a value, it will be overwritten. If the attribute
67+
// path does not have a value, it will be added.
68+
//
69+
// The value must not be an untyped nil. Use a typed nil or types package null
70+
// value function instead. For example with a types.StringType attribute,
71+
// use (*string)(nil) or types.StringNull().
72+
//
73+
// Lists can only have the next element added according to the current length.
74+
func (r *Resource) SetAttribute(ctx context.Context, path path.Path, val interface{}) diag.Diagnostics {
75+
// If r is nil, then calling r.data triggers a nil pointer error so we return the error diag here
76+
if r == nil {
77+
return diag.Diagnostics{
78+
diag.NewErrorDiagnostic(
79+
"Missing Resource Definition",
80+
"An unexpected error was encountered when attempting to set a resource attribute. The resource does not indicate support via a resource schema.\n\n"+
81+
"This is always a problem with the provider and should be reported to the provider developer."),
82+
}
83+
}
84+
85+
data := r.data()
86+
diags := data.SetAtPath(ctx, path, val)
87+
88+
if diags.HasError() {
89+
return diags
90+
}
91+
92+
r.Raw = data.TerraformValue
93+
94+
return diags
95+
}
96+
6397
func (r Resource) data() fwschemadata.Data {
6498
return fwschemadata.Data{
6599
Description: fwschemadata.DataDescriptionResource,

0 commit comments

Comments
 (0)