From c1814c3f38ef80e917dc98c515f71bc6ead636ef Mon Sep 17 00:00:00 2001 From: Modular Magician Date: Mon, 27 Mar 2023 03:38:02 +0000 Subject: [PATCH] handle user not found (#7494) * handle user not found * update --------- Co-authored-by: Edward Sun Signed-off-by: Modular Magician --- .changelog/7494.txt | 3 +++ google-beta/resource_sql_user.go | 17 ++++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 .changelog/7494.txt diff --git a/.changelog/7494.txt b/.changelog/7494.txt new file mode 100644 index 0000000000..1870c3b338 --- /dev/null +++ b/.changelog/7494.txt @@ -0,0 +1,3 @@ +```release-note:bug +cloudsql: fixed the error in any subsequent apply on `google_sql_user` after its `google_sql_database_instance` is deleted +``` diff --git a/google-beta/resource_sql_user.go b/google-beta/resource_sql_user.go index fc835c7bd3..92f04b4a6c 100644 --- a/google-beta/resource_sql_user.go +++ b/google-beta/resource_sql_user.go @@ -6,6 +6,7 @@ import ( "strings" "time" + "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" sqladmin "google.golang.org/api/sqladmin/v1beta4" @@ -23,6 +24,19 @@ func diffSuppressIamUserName(_, old, new string, d *schema.ResourceData) bool { return false } +func handleUserNotFoundError(err error, d *schema.ResourceData, resource string) error { + if IsGoogleApiErrorWithCode(err, 404) || IsGoogleApiErrorWithCode(err, 403) { + log.Printf("[WARN] Removing %s because it's gone", resource) + // The resource doesn't exist anymore + d.SetId("") + + return nil + } + + return errwrap.Wrapf( + fmt.Sprintf("Error when reading or editing %s: {{err}}", resource), err) +} + func ResourceSqlUser() *schema.Resource { return &schema.Resource{ Create: resourceSqlUserCreate, @@ -306,7 +320,8 @@ func resourceSqlUserRead(d *schema.ResourceData, meta interface{}) error { return err }, 5) if err != nil { - return handleNotFoundError(err, d, fmt.Sprintf("SQL User %q in instance %q", name, instance)) + // move away from handleNotFoundError() as we need to handle both 404 and 403 + return handleUserNotFoundError(err, d, fmt.Sprintf("SQL User %q in instance %q", name, instance)) } var user *sqladmin.User