How to reference resources using for_each and map

Below is my variables.tf

variable "storageaccounts"  {
  type = "map"
  default = {
    sa1 = {
      name = "sa1test"
      location = "westeurope"
      account_kind = "StorageV2"
      account_tier = "Standard"
      account_replication_type = "LRS"
      access_tier = "Hot"
      resource_group_name = "bla"
    }
    
    sa2 = {
      name = "sa2test"
      location = "westeurope"
      account_kind = "StorageV2"
      account_tier = "Standard"
      account_replication_type = "LRS"
      access_tier = "Cool"
      resource_group_name = "bla2"
    }
  }
}

I created the below resources

resource "azurerm_resource_group" "rg" {
  for_each = "${var.storageaccounts}"
  name     = "${each.value.resource_group_name}"
  location = "${each.value.location}"
}

resource "azurerm_storage_account" "storageaccounts" {
  for_each                  = "${var.storageaccounts}"
  name                      = "${each.value.name}"
  resource_group_name       = "${each.value.resource_group_name}"
  location                  = "${each.value.location}"
  account_replication_type  = "${each.value.account_replication_type}"
  account_tier              = "${each.value.account_tier}"
}

How to create the resourcegroups first without the use of depends_on

Hi @dkooll,

This is a funny situation because the data flow doesn’t automatically imply the correct dependency order here, but to address it I’d probably write the azurerm_storage_account configuration as if the resource group name and location were not predictable in this way, and thus ultimately get the same values but also let Terraform see the dependency:

resource "azurerm_resource_group" "rg" {
  for_each = var.storageaccounts

  name     = each.value.resource_group_name
  location = each.value.location
}

resource "azurerm_storage_account" "storageaccounts" {
  for_each = var.storageaccounts

  name                      = each.value.name
  resource_group_name       = azurerm_resource_group.rg[each.key].name
  location                  = azurerm_resource_group.rg[each.key].location
  account_replication_type  = each.value.account_replication_type
  account_tier              = each.value.account_tier
}

This feels a little artificial because in Azure the unique identifier for a resource group is just its name, which you already knew in order to specify it in the first place. But instead of saying "use the resource group name from var.storageaccounts" we can say "use the name of the corresponding instance of azurerm_resource_group.rg", getting the same ultimate result but making sure the resource group creation completes first.

1 Like