hashicorp / terraform-provider-google

Terraform Provider for Google Cloud Platform
https://registry.terraform.io/providers/hashicorp/google/latest/docs
Mozilla Public License 2.0
2.35k stars 1.75k forks source link

Automatically generate code to skip update requests if only client-side fields are modified #18964

Open melinath opened 3 months ago

melinath commented 3 months ago

What kind of contribution is this issue about?

Other (specify in details)

Details

If only client-side fields were modified, you can short-circuit the Update function to avoid sending an API request. This is important because the update request will be empty (which causes errors for some APIs.)

For handwritten resources, this needs to be added per-resource (https://github.com/hashicorp/terraform-provider-google/issues/13820) but for generated resources it should be possible to automatically generate this code. The code can live at the top of the Update function and should look something like this:

clientSideFields := map[string]bool{"deletion_protection": true}
clientSideOnly := true
for field := range ResourceSpannerInstance().Schema {
    if d.HasChange(field) && !clientSideFields[field] {
        clientSideOnly = false
        break
    }
}
if clientSideOnly {
    return nil
}

The value of clientSideFields could be autogenerated to include all fields in virtual_fields.

Note: Terraform automatically updates the state based on the plan; this does not need to happen in the Update function unless the value for a field might have changed (for example, based on an API response, which doesn't apply to client-side fields).

References

PR that documents this best practice for handwritten resources: https://github.com/GoogleCloudPlatform/magic-modules/pull/11330

melinath commented 3 months ago

Note from triage: 66 MMv1 resources currently have virtual_fields set.