CodexBloom - Programming Q&A Platform

Terraform 1.4.3: scenarios Handling with `for_each` on Dynamic Resource Creation in Azure

👀 Views: 85 💬 Answers: 1 📅 Created: 2025-08-30
terraform azure infrastructure-as-code HCL

I'm working on a project and hit a roadblock... I'm stuck on something that should probably be simple. I'm working with an scenario with dynamically creating Azure resources using the `for_each` argument in my Terraform configuration. Specifically, I want to create multiple Azure Storage Accounts based on a map of configurations, but I'm running into a question where Terraform seems to skip the creation of some resources and throws the following behavior: ``` behavior: behavior creating Storage Account "myaccount1": storage.AccountsClient#Create: Failure responding to request: StatusCode=404 -- Original behavior: autorest/validation: Validation failed: - Name want to be empty, invalid characters, or more than 24 characters ``` Here's a simplified version of my configuration: ```hcl variable "storage_accounts" { type = map(object({ name = string location = string sku = string })) default = { "account1" = { name = "mystorageaccount1", location = "East US", sku = "Standard_LRS" }, "account2" = { name = "invalid_account_name!", location = "East US", sku = "Standard_LRS" }, } } resource "azurerm_storage_account" "example" { for_each = var.storage_accounts name = each.value.name resource_group_name = azurerm_resource_group.example.name location = each.value.location account_tier = each.value.sku account_replication_type = "LRS" } ``` I’ve double-checked that the names of the storage accounts conform to Azure's requirements, and I've made sure there are no unsupported characters. Yet, I suspect the invalid name in my map is what's causing the entire operation to unexpected result. I attempted to filter out invalid entries using a local value but that hasn't worked as expected: ```hcl locals { valid_storage_accounts = { for k, v in var.storage_accounts : k => v if can(v.name) && !contains(v.name, "!") } } ``` When I replace `for_each = var.storage_accounts` with `for_each = local.valid_storage_accounts`, it throws a different behavior about the `count` argument being invalid. Any advice on how to handle this situation properly so that I can skip invalid configurations without causing the entire apply to unexpected result would be greatly appreciated. I'd really appreciate any guidance on this. This issue appeared after updating to Hcl stable. What would be the recommended way to handle this? I've been using Hcl for about a year now. Thanks, I really appreciate it!