Skip to content

[BUG]: github_branch delete fails with 422 when branch already deleted outside Terraform #3253

@shreyasbharath

Description

@shreyasbharath

Expected Behavior

When Terraform destroys a github_branch resource and the branch has already been deleted outside of Terraform (e.g. manually or via merge settings), the delete should succeed as a no-op since the desired state (branch gone) is already achieved.

Actual Behavior

The delete fails with:

Error: error deleting GitHub branch reference Org/repo (refs/heads/develop): DELETE https://api.github.com/repos/Org/repo/git/refs/heads/develop: 422 Reference does not exist []

Terraform Version

1.6.x

Affected Resource(s)

  • github_branch

Steps to Reproduce

  1. Create a github_branch resource for a branch (e.g. develop)
  2. Delete the branch outside of Terraform (manually, or via GitHub's "delete branch on merge" setting)
  3. Remove the branch from managed_branches in your Terraform config
  4. Run terraform apply
  5. Terraform tries to destroy the github_branch resource and fails with 422

Root Cause

The resourceGithubBranchDelete function does not handle the case where the branch reference no longer exists:

func resourceGithubBranchDelete(d *schema.ResourceData, meta any) error {
	// ...
	_, err = client.Git.DeleteRef(ctx, orgName, repoName, branchRefName)
	if err != nil {
		return fmt.Errorf("error deleting GitHub branch reference %s/%s (%s): %w",
			orgName, repoName, branchRefName, err)
	}
	return nil
}

Note that resourceGithubBranchRead already handles 404 correctly by removing the resource from state. The delete function should similarly treat a 404 or 422 "Reference does not exist" as a successful deletion.

Suggested Fix

_, err = client.Git.DeleteRef(ctx, orgName, repoName, branchRefName)
if err != nil {
	var ghErr *github.ErrorResponse
	if errors.As(err, &ghErr) {
		if ghErr.Response.StatusCode == http.StatusNotFound ||
			ghErr.Response.StatusCode == http.StatusUnprocessableEntity {
			// Branch already deleted, treat as success
			return nil
		}
	}
	return fmt.Errorf("error deleting GitHub branch reference %s/%s (%s): %w",
		orgName, repoName, branchRefName, err)
}

Happy to open a PR for this if it looks reasonable.

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions