From 1fd9311b9e4a265efbeaa48c6197efa435539b67 Mon Sep 17 00:00:00 2001 From: cytopia Date: Thu, 3 Mar 2022 21:52:46 +0100 Subject: [PATCH] Remove team from state if deletion failed and it does not exist (#1039) --- 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 7f932b7a55..9f4c0f194c 100644 --- a/github/resource_github_team.go +++ b/github/resource_github_team.go @@ -239,6 +239,29 @@ func resourceGithubTeamDelete(d *schema.ResourceData, meta interface{}) error { ctx := context.WithValue(context.Background(), ctxId, 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 }