How should Read() signal that a resource has vanished from the API server?

Hi @bumble :wave: Welcome to the HashiCorp Discuss community and thank you for posting this question.

Properly signaling resource existence across the resource lifecycle can be summarized as:

  • Create: Return error diagnostics for any “resource not found” errors (e.g. if there are reads for additional information). Returning an error during creation will automatically taint a resource in Terraform, which will ensure its recreated next apply operation so that configured provisioners can be run.
  • Delete: Ignore “resource not found” errors. Since this operation was intended to remove the resource already, there is generally no need to return an error.
  • Read: Remove the resource from the state on “resource not found” errors. Terraform will automatically take this provider feedback to recreate a new resource on the next apply operation.
  • Update: Always return error diagnostics for any “resource not found” errors. This will ensure the practitioner exactly knows about any potentially unexpected issue during the update process. The next time that Terraform runs, the Read functionality will catch the missing resource as mentioned above.

In terraform-plugin-framework, you can remove a resource from state by calling the response type State field RemoveResource() method. So given the following resource code:

func (r exampleResource) Read(ctx context.Context, req tfsdk.ReadResourceRequest, resp *tfsdk.ReadResourceResponse) {
  // ... other logic to call API/client ...

  if /* "resource not found" error */ {
    resp.State.RemoveResource()
    return
  }

  // ... other logic to update resp.State from API/client ...
}

Does this help answer your question?

1 Like