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)
Steps to Reproduce
- Create a
github_branch resource for a branch (e.g. develop)
- Delete the branch outside of Terraform (manually, or via GitHub's "delete branch on merge" setting)
- Remove the branch from
managed_branches in your Terraform config
- Run
terraform apply
- 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
Expected Behavior
When Terraform destroys a
github_branchresource 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:
Terraform Version
1.6.x
Affected Resource(s)
github_branchSteps to Reproduce
github_branchresource for a branch (e.g.develop)managed_branchesin your Terraform configterraform applygithub_branchresource and fails with 422Root Cause
The
resourceGithubBranchDeletefunction does not handle the case where the branch reference no longer exists:Note that
resourceGithubBranchReadalready 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
Happy to open a PR for this if it looks reasonable.
References