I am attempting to add multiple roles to a GCP group in multiple projects via Terraform. I've skimmed through documentation, other threads here, and have attempted multiple trial/error attempts with no luck.
Below is what I have:
vars.tf
variable "specific_group" {
type = string
default = "group:specificgroup@domain.com"
}
variable "group_bigtable_roles" {
type = list(string)
default = [
"roles/bigtable.admin",
"roles/cloudfunctions.developer",
"roles/cloudscheduler.admin",
"roles/deploymentmanager.editor",
]
}
locals.tf
locals {
...
bigtable = {
project1 = "123"
project2 = "456"
project3 = "789"
...
}
}
specificgroup.tf
resource "google_project_iam_member" "specific_group_bigtable_roles" {
for_each = local.projects.bigtable
project = each.key
member = var.specific_group
count = length(var.group_bigtable_roles)
role = "var.group_bigtable_roles[count.index]"
}
I am currently getting an error that the resource (in specificgroup.tf) can only explicitly have for_each or count. I understand the reasoning for that error, but I've tried to do nested for_each and other things with no luck either. Is it possible to have separate for_each's in the same resource? I feel like I'm getting somewhere but it's currently just a brick wall to me. Any help or guidance is appreciated!
The solution is to create a list of combinations so you only need one for_each:
variable "specific_group" {
type = string
default = "group:specificgroup@domain.com"
}
variable "group_bigtable_roles" {
type = list(string)
default = [
"roles/bigtable.admin",
"roles/cloudfunctions.developer",
"roles/cloudscheduler.admin",
"roles/deploymentmanager.editor",
]
}
variable "group_bigtable_projects" {
type = list(string)
default = [
"123",
"456",
"789"
]
}
locals {
project_role_combination_list = distinct(flatten([
for project in var.group_bigtable_projects : [
for role in var.group_bigtable_roles : {
project = project
role = role
}
]
]))
}
resource "google_project_iam_member" "specific_group_bigtable_roles" {
for_each = { for entry in local.project_role_combination_list: "${entry.project}.${entry.role}" => entry }
project = each.value.project
role = each.value.role
member = var.specific_group
}