I am trying to create multiple Azure Storage accounts with specific Azure File shares under each account using the variable type as map:object. I have created the following terraform code but getting the error message:
- CODE
StorageAccount = {
"dev" = {
SName = "test"
SAFileShare = [logs1", "Logs3"]
}
"prd" = {
SName = "test1"
SAFileShare = ["Logs3", "logs4"]
}
}
variable "StorageAccount" {
type = map(object({
SName = string
SAFileShare = list(string)
SABlob = list(string)
}))
}
# Storage Account
resource "azurerm_storage_account" "Storage" {
for_each = var.StorageAccount
name = lower(join("", [var.AppShortName, join(each.value["SName"], [var.EnvironmentType, "sa"])]))
location = var.Location
resource_group_name = azurerm_resource_group.ResourceGroup.name
account_tier = var.accountTier
account_replication_type = var.accountReplicationType
}
# File Share
resource "azurerm_storage_share" "FileShare" {
for_each = var.StorageAccount
name = each.value["SAFileShare"]
storage_account_name = azurerm_storage_account.Storage[each.key].name
quota = 50
}
- Error Message
Error: Incorrect attribute value type
│
│ on main.tf line 4, in resource "azurerm_storage_share" "FileShare":
│ 4: name = each.value["SAFileShare"]
│ ├────────────────
│ │ each.value["SAFileShare"] is list of string with 2 elements
│
│ Inappropriate value for attribute "name": string required.
2
Answers
You are getting this error because of how you are creating the Azure File Shares. The
name
attribute of theazurerm_storage_share
resource requires a string, but you are giving it a list of strings witheach.value["SAFileShare"]
. Terraform will not create multiple file shares by looping over this list automatically.I was having trouble with the
for_each
expression and the dynamic property, so I tried this solution, which seems to meet the requirement for now.My demo terraform configruation:
Output:
you can use merge function for looping twice in map of objects.
here’s what you can do:
This can be used to create multiple file share in certain storage accounts as you wanted.