Terraform create multiple resources using for_each and jsondecode

Viewed 22

I want to create multiple resource(GCP's multiple cloudSQL instances) and this is what I have:

locals {
  psql_settings = [
    { "name" : "psql1", "location" : "us-central1", "zone" : "us-central1-c" },
    { "name" : "psql2", "location" : "us-east1", "zone" : "us-east1-b" }
  ]
}

I have to use them in json format because this will be stored in consul for dynamic changes.

Using this locals value, how I can create multiple resources. I am trying:

module "postgresql-db" {
  depends_on = [
    module.vpc
  ]
  source               = "../modules/postgres"
  for_each             = local.psql_settings[0]
  name                 = each.value.name
  random_instance_name = true
  database_version     = "POSTGRES_13"
  project_id           = "xyz-project
  zone                 = each.value.zone
  region               = each.value.location
...
...
1 Answers

It should be:

  for_each   = {for idx,val in local.psql_settings: idx => val}

The code changes your list of maps, into map of maps, which is required by for_each.

Related