How to update branch protection using Terraform without remote branch in GITHUB?

Viewed 1010

I need to create the CI/CD pipelines and protect some specific branches in GITHUB for a lot of repositories. But if the remote branch doesn't exists I get an error.

It works only if I have already created the remote branch in GITHUB. But I need to do it all through Terraform or an automated way.

# Configure the GitHub Provider
provider "github" {
  token        = "${var.github_token}"
  organization = "${var.github_organization}"
}

# Protect the CI/CD branch of the foo repository
resource "github_branch_protection" "foo" {
  repository     = "foo"
  branch         = "staging"
  enforce_admins = true

  required_pull_request_reviews {
   required_approving_review_count = 2
  }

}

Terraform result with GITHUB remote branch:

github_branch_protection.foo: Creating...
github_branch_protection.foo: Creation complete after 3s [id=foo:staging]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

(Actual error) Terraform result without GITHUB remote branch:

Error: PUT https://api.github.com/repos/jetprogramming/foo/branches/staging/protection: 404 Branch not found []
2 Answers

You cannot do this as branch protection is a property of a branch. If the branch does not exist you cannot enable it's branch protection property as you cannot set a property of non-existing object. This feature was introduced as in GitHub flow it is common practice to protect master branch (which is created when you create repository) so the only way to introduce changes to it is through pull request that needs to be approved first.

What you can do for now (as temporary solution) is to first create repository (with terraform) then create branches (with some script using github api) and then apply enable branch protection with terraform.

Furthermore I would also recommend you add describe your usecase in an issue on github page of terraform github provided and request feature to create branches which should solve your problem.

If it's a brand new repository being created by terraform, you can get around this by setting the default_branch = staging and auto_init = true

That way the branch will exist. It's not elegant, and I don't like it... but it does work around the issue.

If your repo already exists, do not set auto_init = true or your repo is destroyed and recreated.

Related