I have a key – value input with information about GCP projects that need to be created. With information like the name, GCP folder that the project should go in etc.
I want in my terraform code to create the folder of the project if it does not exist.
With a code like this:
module "project-factory" {
source = "terraform-google-modules/project-factory/google"
for_each = local.projects
name = each.key
org_id = each.value.org_id
folder_id = google_folder.team[each.key].name
.
.
.
}
resource "google_folder" "team" {
for_each = local.projects
display_name = each.value.folder
parent = var.parent
}
That creates the problem of course, that if multiple projects have the same folder to go in, the creation to fail because the folder is already created.
I guess I can do some – unwanted – magic with running scripts and importing the folders in my tf.state, but is there any clever solution for the problem?
Thank you!
When multiple projects use the same folder, the folder creation can fail because Terraform tries to create it multiple times. One efficient and cleaner solution is to deduplicate the folders and ensure that each folder is created only once.
Use Terraform’s for_each combined with a set of unique folder names.
locals {
unique_folders = tomap({
for project_key, project in local.projects :
project.folder => project
})
}
resource "google_folder" "team" {
for_each = local.unique_folders
display_name = each.key
parent = var.parent
}
module "project-factory" {
source = "terraform-google-modules/project-factory/google"
for_each = local.projects
name = each.key
org_id = each.value.org_id
# Lookup folder ID from the created folders
folder_id = google_folder.team[each.value.folder].name
# Other configurations...
}