Framework's alternative to HasChange()

Hi!

In Terraform SDK we had HasChange() method to optionally update only changing attributes, like in

if d.HasChange(“service_name”) {
srv.SetServiceName(d.Get(“service_name”).(string))
}

How can I implement the same logic using the framework? At the moment my provider tries to apply all the attributes in the plan, even if the values stay the same.

Thanks

1 Like

Hi @mkuzmin :wave: Welcome to HashiCorp Discuss and thank you for posting this. Apologies that this is not well documented at the moment. I have created Document Resource Update HasChange Equivalent · Issue #527 · hashicorp/terraform-plugin-framework · GitHub to address that issue.

To accomplish something similar in the framework, you can compare the plan and prior state data values from the resource.UpdateRequest type Plan and State fields.

If using a schema data model type:

type ThingResourceModel struct {
  ServiceName types.String `tfsdk:"service_name"`
  // ...
}

// Update logic
var plan, state ThingResourceModel

resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)

if resp.Diagnostics.HasError() {
  return
}

if !plan.ServiceName.Equal(state.ServiceName) {
  srv.SetServiceName(plan.ServiceName.ValueString())
}

If working with individual attributes, it is a more verbose as more attributes are compared:

// Update logic
var serviceNamePlan, serviceNameState types.String

resp.Diagnostics.Append(req.Plan.GetAttribute(ctx, path.Root("service_name"), &serviceNamePlan)...)
resp.Diagnostics.Append(req.State.GetAttribute(ctx, path.Root("service_name"), &serviceNameState)...)

if resp.Diagnostics.HasError() {
  return
}

if !serviceNamePlan.Equal(serviceNameState) {
  srv.SetServiceName(serviceNamePlan.ValueString())
}

Hope this helps and please reach out if you have further questions.

1 Like

Sorry for bumping up an old thread, but is there similar equivalent for sdkv2 HasChangesExcept() function?