google cloud platform – Create GCP folder with Terraform only if it does not exist

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!

Read more here: Source link