From e710910474b3043e1141a8dcfc9037f140d7dd01 Mon Sep 17 00:00:00 2001 From: cytopia Date: Mon, 17 Jan 2022 14:31:10 +0100 Subject: [PATCH] Remove team from state if deletion failed and it does not exist --- github/resource_github_team.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/github/resource_github_team.go b/github/resource_github_team.go index b8d2e6628f..3fa2047276 100644 --- a/github/resource_github_team.go +++ b/github/resource_github_team.go @@ -243,6 +243,29 @@ func resourceGithubTeamDelete(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Deleting team: %s", d.Id()) _, err = client.Teams.DeleteTeamByID(ctx, orgId, id) + /* + When deleting a team and it failed, we need to check if it has already been deleted meanwhile. + This could be the case when deleting nested teams via Terraform by looping through a module + or resource and the parent team might have been deleted already. If the parent team had + been deleted already (via parallel runs), the child team is also already gone (deleted by + GitHub automatically). + So we're checking if it still exists and if not, simply remove it from TF state. + */ + if err != nil { + // Fetch the team in order to see if it exists or not (http 404) + _, _, err = client.Teams.GetTeamByID(ctx, orgId, id) + if err != nil { + if ghErr, ok := err.(*github.ErrorResponse); ok { + if ghErr.Response.StatusCode == http.StatusNotFound { + // If team we failed to delete does not exist, remove it from TF state. + log.Printf("[WARN] Removing team: %s from state because it no longer exists", + d.Id()) + d.SetId("") + return nil + } + } + } + } return err }