Skip to content

fix: skip github_team_members deletion when parent team is already gone - #3461

Merged
deiga merged 14 commits into
integrations:mainfrom
nitinjain999:fix/skip-team-members-delete-on-team-gone
Jun 18, 2026
Merged

deiga merged 14 commits into
integrations:mainfrom
nitinjain999:fix/skip-team-members-delete-on-team-gone

Conversation

@nitinjain999

@nitinjain999 nitinjain999 commented May 30, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #3411


Before the change?

When github_team and github_team_members are destroyed together, the team deletion removes all members server-side. The subsequent github_team_members destroy makes N individual RemoveTeamMembershipByID API calls that all return 404 and fail loudly.

Additionally, if a team is deleted outside of Terraform, the next terraform plan or terraform refresh would not remove github_team_members from state — it would either error or silently return an empty member list, causing a perpetual diff.

After the change?

Delete: On a 404 from RemoveTeamMembershipBySlug/RemoveTeamMembershipByID, the function returns cleanly. The GitHub API returns 204 (not 404) when a membership doesn't exist, so a 404 exclusively means the team itself is gone mid-delete.

Read: Switched from GraphQL (v4client) to REST (v3client), making two paginated ListTeamMembersByID/Slug calls filtered by role (member and maintainer). A 404 response removes the resource from state cleanly.

All functions (Create, Update, Read, Delete): Use newLegacyTeamIdentity to dispatch to the slug-based or ID-based API methods without an upfront lookup, consistent with the pattern in resource_github_repository_collaborators.

Pull request checklist

  • Schema migrations have been created if needed — not applicable, no schema changes
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been reviewed and added / updated if needed — no doc changes needed, no schema or user-visible behaviour change

Does this introduce a breaking change?

  • Yes
  • No

@github-actions

Copy link
Copy Markdown

👋 Hi, and thank you for this contribution!

This repo is maintained by GitHub and community members on a best-effort basis. We'll get to this as soon as we can.

You can help us prioritize by joining the discussion on open issues and PRs, sharing details on the changes you need, and reviewing other contributions.


🤖 This is an automated message.

@github-actions github-actions Bot added the Type: Bug Something isn't working as documented label May 30, 2026
@nitinjain999
nitinjain999 marked this pull request as ready for review May 30, 2026 19:59
@nitinjain999
nitinjain999 force-pushed the fix/skip-team-members-delete-on-team-gone branch from 013f2fd to 99e1360 Compare May 30, 2026 20:02
When a github_team is destroyed alongside github_team_members, the team
deletion removes all members server-side. Subsequent per-member API calls
return 404 and fail loudly.

Handle 404 from both getTeamID (slug-based lookup) and
RemoveTeamMembershipByID (numeric ID path) by treating them as a no-op
and returning early, consistent with how other resources handle missing
parents.

Fixes integrations#3411
@nitinjain999
nitinjain999 force-pushed the fix/skip-team-members-delete-on-team-gone branch from 99e1360 to 8b8f5f4 Compare May 30, 2026 20:17
@nitinjain999

Copy link
Copy Markdown
Contributor Author

Tested against a real GitHub org (nitin-sv) using make testacc T=TestAccGithubTeamMembers.

The new subtest succeeds_when_parent_team_is_deleted_out-of-band_before_destroy passes — team deleted via API before destroy, Terraform completes cleanly with no 404 error.

The existing creates_a_team_&_members_configured_with_defaults subtest fails in this environment because the test user is an org owner, and GitHub silently promotes owners to maintainer regardless of the requested role. This is a pre-existing issue unrelated to this change and documented in the provider notes.

@stevehipwell stevehipwell added this to the v6.13.0 milestone Jun 3, 2026
@deiga
deiga requested a review from Copilot June 3, 2026 18:08

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

These provider review instructions are being used.

This PR improves the github_team_members resource’s behavior when its parent GitHub team has been deleted (either by Terraform ordering during destroy or out-of-band), by treating “team not found” as a graceful no-op in Delete and removing the resource from state in Read to avoid perpetual diffs.

Changes:

  • Update resourceGithubTeamMembersRead to remove github_team_members from state when the parent team no longer exists (REST 404 during slug lookup, or GraphQL organization.team resolving to null).
  • Update resourceGithubTeamMembersDelete to treat “team not found” as a successful no-op and avoid failing on 404s.
  • Add an acceptance test that deletes the team out-of-band before running destroy.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
github/resource_github_team_members.go Adds 404-aware Read/Delete behavior to gracefully handle missing parent teams and prevent drift/perpetual diffs.
github/resource_github_team_members_test.go Adds an acceptance test scenario for out-of-band team deletion prior to destroy.

Comment thread github/resource_github_team_members.go Resolved
…coverage

- Delete: on 404 from RemoveTeamMembershipByID, verify whether the team
  itself is gone before short-circuiting; if team still exists the
  membership was removed out-of-band so skip that user and continue
  the loop rather than skipping all remaining members
- Test: add RefreshState step after out-of-band team deletion to assert
  github_team_members is removed from state by Read, covering the new
  getTeamSlug 404 and DatabaseId==0 guard paths
@nitinjain999

Copy link
Copy Markdown
Contributor Author

Addressed both Copilot review comments:

Delete logic (line 297): On a 404 from RemoveTeamMembershipByID, the code now calls GetTeamByID to distinguish between "team is gone" and "just this membership was removed out-of-band". If the team is gone it short-circuits; if the team still exists it skips that one user and continues the loop.

Test coverage (line 102): Added a RefreshState: true step that deletes the team out-of-band via PreConfig, then asserts the refresh removes github_team_members from state cleanly — covering both the getTeamSlug 404 and DatabaseId==0 guard paths in Read. Verified passing locally against nitin-sv.

Comment thread github/resource_github_team_members.go Resolved
nitinjain999 and others added 3 commits June 16, 2026 07:55
… test

Ensures the context is cancelled when the test ends for correct cleanup.
… behavior

RemoveTeamMembershipByID returns 204 (not 404) when a membership doesn't
exist, so a 404 exclusively indicates the team itself is gone. Remove the
unnecessary secondary GetTeamByID check and the incorrect drift-handling
branch that could never fire.

Verified locally against nitin-sv: removing a non-member returns 204;
removing from a deleted team returns 404.
@nitinjain999

Copy link
Copy Markdown
Contributor Author

Addressing @deiga's comment on the 404 behavior:

You're right. I verified directly against the GitHub API: RemoveTeamMembershipByID (DELETE /organizations/{orgId}/team/{teamId}/memberships/{username}) returns 204 when the membership doesn't exist for a real GitHub user — a 404 exclusively indicates the team itself is gone.

The secondary GetTeamByID check and the incorrect drift-handling continue branch have been removed. A 404 now immediately short-circuits the delete loop without an extra API call.

Also verified with a live acceptance test against a real org. ✅ Fixed

Comment thread github/resource_github_team_members.go Resolved
@nitinjain999

Copy link
Copy Markdown
Contributor Author

Hey @deiga, the getTeamID call can't be removed — it's not just a team-existence check, it's also a slug resolver. The team_id attribute accepts either a numeric ID or a team slug, and RemoveTeamMembershipByID requires an int64. If someone passed a slug as team_id, skipping this would break deletion entirely regardless of team state.

The 404 guard there is a side benefit: if the team's already gone before we start, we bail immediately instead of firing N membership deletes and getting N 404s back.

That said — are you thinking there's a way to avoid the extra API call when team_id is already numeric? In that case getTeamID does a local parse with no network call (parseTeamID), so it's free. The extra call only happens for slug-based IDs. Does that change your thinking?

@stevehipwell

stevehipwell commented Jun 16, 2026 •

Copy link
Copy Markdown
Collaborator

I think a better fix for the read part would be to switch to using the REST client as I can't see any reason to use the GraphQL client. Our default posture is to use the REST client wherever possible.

@stevehipwell

Copy link
Copy Markdown
Collaborator

@nitinjain999 RE ID vs slug you can use newLegacyTeamIdentity to handle both cases.

t := newLegacyTeamIdentity(teamID)
if slug, ok := t.getSlugOK(); ok {
	// Use non-legacy slug method
} else {
	id := t.getID()
	// Use legacy ID method
}

@nitinjain999

Copy link
Copy Markdown
Contributor Author

Thanks @stevehipwell.

On the Read refactor to REST: understood, will switch to v3client. The current GraphQL query fetches members with roles in one call; the REST equivalent would be ListTeamMembersByID/Slug for the member list, then GetTeamMembershipByID/Slug per user for their role — so it becomes N+1 calls instead of one. Is that the expected tradeoff, or is there a way to get member roles in a single REST call I'm missing?

On newLegacyTeamIdentity for Delete: will apply that pattern, thanks for pointing to it.

…ndling

Replace the upfront getTeamID call with newLegacyTeamIdentity, dispatching
to RemoveTeamMembershipBySlug or RemoveTeamMembershipByID based on whether
team_id is a slug or numeric ID. This removes an unnecessary pre-loop API
call and aligns with the existing pattern in resource_github_repository_collaborators.
@nitinjain999
nitinjain999 requested a review from Copilot June 16, 2026 18:21
@stevehipwell

Copy link
Copy Markdown
Collaborator

@nitinjain999 you can use the newLegacyTeamIdentity pattern in all of the functions to save additional calls to lookup the ID. RE the REST API, you can make two calls to get the users filtered by role.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

…tity across all functions

Replace GraphQL (v4client) in Read with two REST calls filtered by role
(member/maintainer) via ListTeamMembersByID/Slug, aligning with the
provider default posture of using v3client.

Apply newLegacyTeamIdentity in Create, Update, and Read to dispatch to
the slug-based or ID-based API methods without an upfront lookup call,
consistent with the pattern in resource_github_repository_collaborators.
@nitinjain999

nitinjain999 commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor Author

@stevehipwell Both suggestions applied

  1. newLegacyTeamIdentity across all functions — Create, Update, Read, and Delete now all use newLegacyTeamIdentity to dispatch to the slug or ID-based API method directly, no upfront lookup needed.

  2. Read switched to REST — replaced the GraphQL v4client query with two paginated ListTeamMembersByID/Slug calls filtered by role (member and maintainer). A 404 removes the resource from state cleanly. This also eliminates the getTeamSlug pre-call and the DatabaseId == 0 null-team guard that were needed before.

Tested against nitin-sv, the out-of-band team deletion acceptance test passes.

@stevehipwell stevehipwell left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is looking good @nitinjain999. I've added some inline feedback, I also think it's worth replacing calls to log with tflog.

Comment thread github/resource_github_team_members.go Resolved
Comment thread github/resource_github_team_members.go Resolved
Comment thread github/resource_github_team_members.go Resolved
- Use Iter methods for pagination in Read — replaces manual next-page loop
- Return nil from Create and Update instead of calling Read inline
@nitinjain999

nitinjain999 commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor Author

@stevehipwell All three addressed in the latest commit:

  • Create/Update: both now return nil directly instead of calling Read inline.
  • Read pagination: switched to ListTeamMembersByIDIter/ListTeamMembersBySlugIter — the manual next-page loop is gone.

Tested, passing.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

@stevehipwell stevehipwell left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick responses @nitinjain999, the code structure is looking good so we should be ready to approve/merge once you've fixed the lint issues.

@stevehipwell

Copy link
Copy Markdown
Collaborator

@nitinjain999 it still looks like there are a few lint issues, the exact pattern for errors.AsType is in the contribution guide.

@nitinjain999

Copy link
Copy Markdown
Contributor Author

Switched to errors.AsType[*github.ErrorResponse](err) as documented in ARCHITECTURE.md — missed that the project uses its own generic helper rather than stdlib errors.As. Both Read and Delete updated. Lint passes locally with .golangci.strict.yml. ✅ Fixed

Replace direct type assertions err.(*github.ErrorResponse) with the
project-standard errors.AsType[*github.ErrorResponse](err) pattern
(documented in ARCHITECTURE.md) in both Read and Delete.
@nitinjain999
nitinjain999 force-pushed the fix/skip-team-members-delete-on-team-gone branch from 55cad6f to b6fb7d9 Compare June 18, 2026 14:54
@stevehipwell

Copy link
Copy Markdown
Collaborator

Switched to errors.AsType*github.ErrorResponse as documented in ARCHITECTURE.md — missed that the project uses its own generic helper rather than stdlib errors.As. Both Read and Delete updated. Lint passes locally with .golangci.strict.yml. ✅ Fixed

@nitinjain999 errors.AsType is part of the Go stdlib.

@nitinjain999

Copy link
Copy Markdown
Contributor Author

Thanks for the correction — I mistakenly assumed it was a project helper. Good to know it's stdlib since Go 1.23.

Both functions became dead code after Read and Delete were switched to
use newLegacyTeamIdentity, which handles slug/ID dispatch locally.
@nitinjain999

nitinjain999 commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor Author

@stevehipwell : Removed getTeamSlug and lookupTeamSlug from util_team.go — both became dead code once all functions were switched to newLegacyTeamIdentity. ✅ Fixed

@stevehipwell stevehipwell left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@nitinjain999
nitinjain999 requested a review from deiga June 18, 2026 15:07
@nitinjain999

Copy link
Copy Markdown
Contributor Author

LGTM

i need to wait for @deiga

@deiga
deiga merged commit ce82972 into integrations:main Jun 18, 2026
10 checks passed
corymhall pushed a commit to pulumi/pulumi-github that referenced this pull request Aug 14, 2026
Unblocks the nightly `upgrade-provider` job and pulls in upstream
v6.13.0.

## Why this was stuck

Upstream v6.13.0 refactored the provider entry point in
[#3440](integrations/terraform-provider-github#3440),
replacing the parameterless `github.Provider()` with
`github.NewProvider(version, commit)`, which returns the provider
factory.

The nightly [Upgrade
provider](https://github.com/pulumi/pulumi-github/actions/workflows/upgrade-provider.yml)
job rebases onto the new tag fine, then dies in codegen:

```
./scripts/upstream.sh rebase -o refs/tags/v6.13.0: done
error: upgrade-provider executed `make tfgen` which failed: exit status 2:
./resources.go:78:33: undefined: github.Provider
make: *** [Makefile:323: bin/pulumi-tfgen-github] Error 1
```

It has failed every night since v6.13.0 was released on 2026-07-08, so
the bridge is still pinned to upstream v6.12.1 and none of the fixes
below have shipped.

## Changes

- `provider/resources.go`: use `github.NewProvider(version.Version,
"")()`. `version` and `commit` only feed the upstream User-Agent and
debug logging; the bridge appends its own Pulumi User-Agent, so the
commit is left empty. This is the only hand-written change.
- `upstream`: v6.12.1 → v6.13.0 (via `upstream.sh checkout` / `rebase -o
refs/tags/v6.13.0` / `check_in`).
- Regenerated schema, all five SDKs, and `docs/_index.md`.

## Notable upstream fixes pulled in

- **`github_team_repository` delete now treats a 404 from GitHub as a
successful delete**
([#3524](integrations/terraform-provider-github#3524)).
Previously the 404 branch only recovered from repository *renames*: it
re-read the repo and retried the delete only when `.GetName()` differed.
A repository transferred to a **different organization** keeps its name,
so the retry was skipped and the original 404 surfaced as a hard error.
Any stack still holding that resource in state is then permanently
wedged — every subsequent update fails on the same undeletable resource,
and the only escape is `pulumi state delete`.
- Fixes a nil-pointer panic in that same delete path when the API call
fails at the transport layer
([#3518](integrations/terraform-provider-github#3518)).
- `github_team_members` deletion is skipped when the parent team is
already gone
([#3461](integrations/terraform-provider-github#3461)).

## Schema impact

Additive — nothing removed or retyped (verified by diffing schema keys
against `master`):

- New provider config options: `cachePath`, `legacyClient`
- New resource properties: `BranchDefault.repositoryId`,
`BranchDefault.waitForRename`,
`RepositoryCollaborators.ownerConfigured`,
`RepositoryCustomProperty.repositoryId`, `TeamMembers.teamSlug`

The bulk of the schema and `docs/_index.md` diff is upstream's migration
to tfplugindocs
([#3380](integrations/terraform-provider-github#3380))
and its rewritten provider docs and examples
([#3440](integrations/terraform-provider-github#3440))
— restyled descriptions, and the overview example changing from
`github_membership` to `getRepository` because upstream replaced
`examples/provider/example_1.tf`/`example_2.tf` with a single
`provider.tf`.

## Verification

- `make tfgen` succeeds; example conversion 93.39% (1314/1407)
- All five SDKs generated; Go SDK compiles
- `dotnet build` not run locally (unrelated local NuGet source
misconfiguration) — leaving that to CI
- Acceptance tests not run locally

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Type: Bug Something isn't working as documented

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[MAINT]: Skip github_team_members deletion when the associated github_team is deleted

4 participants