Home > front end >  Terraform - Use for_each with a list of strings inside tuple
Terraform - Use for_each with a list of strings inside tuple

Time:03-11

I am trying to create multiple data factory linked services, one for each database inside an account.

variables.tf

variable "cosmosdbs" {
  type = any
}

vars.tfvars

cosmosdbs = [
  {
    name = "account1"
    resource_group = "group-name1"
    databases = ["database"]
  },
  {
    name = "account2"
    resource_group = "group-name2"
    databases = ["database1","database2","database3"]
  }
]

main.tf

data "azurerm_cosmosdb_account" "cosmosdbs" {
  for_each            = {for r in var.cosmosdbs: r.name => r}
  name                = each.key
  resource_group_name = each.value.resource_group
}

module "linked_cosmosdbs" {
  source                   = "../"
  for_each                 = {for r in var.cosmosdbs: r.name => r}
  name                     = each.value.databases
  resource_group_name      = module.rg.name
  data_factory_id          = module.adf.id
  description              = "Connection to CosmosDB (Terraformed)"
  integration_runtime_name = local.resource_name
  account_endpoint         = data.azurerm_cosmosdb_account.cosmosdbs[each.key].endpoint
  account_key              = data.azurerm_cosmosdb_account.cosmosdbs[each.key].primary_key
  database                 = each.value.databases
}

Obviously that's not going to work because I want to iterate over each map inside the tuple and for each database create a linked service that belongs to each account.

CodePudding user response:

You have to flatten your variable, for example as:

locals {
  cosmosdbs_flat = merge([
      for val in var.cosmosdbs: {
        for database in val["databases"]: 
            "${val.name}-${database}" => {
                name = val.name
                resource_group = val.resource_group
                database = database
          }
      }
    ]...) # please do NOT remove the dots
}

then

module "linked_cosmosdbs" {
  source                   = "../"
  for_each                 = local.cosmosdbs_flat
  name                     = each.value.database
  resource_group_name      = module.rg.name
  data_factory_id          = module.adf.id
  description              = "Connection to CosmosDB (Terraformed)"
  integration_runtime_name = local.resource_name
  account_endpoint         = data.azurerm_cosmosdb_account.cosmosdbs[each.value.name].endpoint
  account_key              = data.azurerm_cosmosdb_account.cosmosdbs[each.value.name].primary_key
  database                 = each.value.database
}
  • Related