for_Each still deleting other resources

Hi,
I’m changing over to use for_each instead of Count and one of the reasons was for_each doesn’t delete other resources. I’m still getting subnets deleted and recreated when I delete one of my subnets in my map. Please see the code below.

variables.tf

variable “location” {
type = string
default = “UKSouth”
description = “Used to specifiy the location in Azure e.g. UKSouth”
}

variable “resource_group_name” {
type = list(string)
description = “The name of the Resource Group which will contain Management Resources for the Enterprise”
default = [“AAATestOne”, “AAATestTwo”]
}

variable “subnets” {
type = map(string)
default = {
“subnet1” = “10.1.1.0/24”
“subnet2” = “10.1.2.0/24”
“external” = “10.1.0.0/24”
}
}

main.tf

resource “azurerm_resource_group” “main” {
for_each = toset(var.resource_group_name)
name = each.value
location = var.location
}

output “resourcegroups” {
value = azurerm_resource_group.main
}

resource “azurerm_virtual_network” “main” {
name = “test-network”
resource_group_name = azurerm_resource_group.main[“AAATestOne”].name
address_space = [“10.1.0.0/16”]
location = “uksouth”

dynamic “subnet” {
for_each = var.subnets

content {
  name = subnet.key
  address_prefix = subnet.value
}

}
}

output “sub” {
value = azurerm_virtual_network.main
}

If I remove one of the subnets out of the subnet variable, say “external” = “10.1.0.0/24” then when I run terraform plan/apply terraform wants to delete and recreate the other two subnets??

Can someone give me some guidance I thought for_each stopped this issue?

Thanks
Russell

Hi @RussellMaycock,

The handling of count vs. for_each you are thinking of applies to resource count and for_each, which is handled by Terraform itself.

In your example, you’re using a dynamic block to generate multiple subnet blocks, but how those are interpreted is decided by the AzureRM provider rather than by Terraform, regardless of how you write them.

From peeping in the implementation of azurerm_virtual_network I see that it is handling subnet blocks as a set of objects, and so it should be tracking them by their contents rather than by their indices or map keys regardless of whether you use dynamic or static subnet blocks, and so I suspect something else is going on here, not related to dynamic blocks.

Can you share the plan output for when Terraform is proposing to replace all of the subnets? I’d like to understand better exactly what Terraform is proposing here to try to map that back on to how the provider is set up and understand what’s going on here.