Changing default protections for GitLab repositories with Terraform

Hi all,

Sorry if my question is silly, I’m a complete newbie at Terraform. I’m trying to use Terraform to create and manage repositories in GitLab. Let’s assume I have this branch is called “mybranch” and every repo there must have the protections as follows:

resource "gitlab_branch" "mybranch" {
  for_each = { for project in gitlab_project.all : project.name => project }
  name    = "mybranch"
  ref     = "main"
  project = each.value.path_with_namespace
  lifecycle {
    ignore_changes = [
      ref
    ]
  }
}

resource "gitlab_branch_protection" "mybranch" {
  for_each = { for project in gitlab_project.all : project.name => project }
  project                      = each.value.path_with_namespace
  branch                       = "mybranch"
  push_access_level            = "no one"
  merge_access_level           = "developer"
}

Now I want to change the protections for a specific repository, and just for this one, called “special_repo”. The other ones within the branch must remain with the same configuration as before (push level= no one and merge level=developer). I was researching in some commented code by a former engineer a try to do this, but I’m not sure if this will work:

resource "gitlab_branch" "mybranch" {
  for_each = { for project in gitlab_project.all : project.name => project }
  name    = "mybranch"
  ref     = "main"
  project = each.value.path_with_namespace
  lifecycle {
    ignore_changes = [
      ref
    ]
  }
}

resource "gitlab_branch_protection" "mybranch" {
  for_each = { for project in gitlab_project.all : project.name => project }
  project                      = each.value.path_with_namespace
  branch                       = "mybranch"
  push_access_level = each.value.name == "special_repo" ? "no one" : "no one"
  merge_access_level = each.value.name == "special_repo" ? "maintainer" : "developer"
}

The last two lines look to me like some kind of replacement, but to be honest I have no clue about this.

I’d appreciate very much any help on this.

Hello thanks for the post.
The last two lines on the second code fence are ternary operations which are valid in HCL2.
To explain the second line as an example:

merge_access_level = each.value.name == "special_repo" ? "maintainer" : "developer"

means

if each.value.name is equal to the string of text special_repo, then set merge_access_level to maintainer and if each.value.name is not equal to special_repo, then set merge_access_level to developer.

You will notice in the first line

push_access_level = each.value.name == "special_repo" ? "no one" : "no one"

that the ternary expression evaluates to the string no one in either case, which means it would be more concise to write

push_access_level = "no one"

See here: Conditional Expressions - Configuration Language | Terraform | HashiCorp Developer

1 Like

Thank you very much for your clarifying answer!

Kind Regards

Oldman