advanced patterns with Terraform's For_each when Using a Complex Object in Azure
I've tried everything I can think of but I'm building a feature where Hey everyone, I'm running into an issue that's driving me crazy. Quick question that's been bugging me - I'm experiencing unexpected behavior when using `for_each` with a complex object in my Terraform code targeting Azure... I have a module that requires a list of objects with several attributes, and I'm trying to iterate over them to create multiple resources. However, Terraform seems to be treating the values incorrectly, leading to resource creation that does not match my expectations. Here's the relevant snippet of my code: ```hcl variable "vm_configs" { type = list(object({ name = string location = string size = string })) } resource "azurerm_virtual_machine" "example" { for_each = { for vm in var.vm_configs : vm.name => vm } name = each.value.name location = each.value.location vm_size = each.value.size # More configuration... } ``` I initialized the variable `vm_configs` as follows: ```hcl vm_configs = [ { name = "vm1", location = "East US", size = "Standard_DS1_v2" }, { name = "vm2", location = "East US", size = "Standard_DS1_v2" }, { name = "vm3", location = "West US", size = "Standard_DS1_v2" } ] ``` When I run `terraform apply`, it creates the VMs for `vm1` and `vm2` successfully, but it fails with the following behavior for `vm3`: ``` behavior: Invalid configuration: The specified location 'West US' is not available in your subscription. ``` I've double-checked that `West US` is a valid Azure region for my subscription and that I can create resources there. I also tried removing `vm3` from the list and running `terraform apply` again, which worked fine for just `vm1` and `vm2`. To troubleshoot further, I added an output to debug the content of `var.vm_configs`: ```hcl output "debug_vm_configs" { value = var.vm_configs } ``` Looking at the output, everything appears to be correctly formatted. I also ensured that the `azurerm` provider is up to date (version `2.80.0`). Iām not sure why Terraform is throwing an behavior about the location for that specific VM. Has anyone encountered a similar scenario? Any insights on how to resolve this would be appreciated! How would you solve this? This is part of a larger web app I'm building. Any help would be greatly appreciated! The stack includes Hcl and several other technologies. Thanks for any help you can provide! Thanks for taking the time to read this!