Terraform destroy fails, says a module attribute doesn't exist when it does

Hi.

Terraform is failing to destroy resources and I don’t understand why. I am working in Azure but I don’t think this is an Azure-specific error.

I have a networking module which creates several subnets, and an output to expose the subnet IDs for use with other resources:

# module "networking"
variable "subnets" {
  description = "Subnet configuration"
  type        = map(object({
    address_range = list(string)
    name          = string
    delegation    = optional(object({
      name               = string
      service_delegation = object({
        name    = string
        actions = optional(list(string))
      })
    }))
  }))
}

resource "azurerm_subnet" "this" {
  for_each             = var.subnets
  
  name                 = each.value.name
  resource_group_name  = var.rg_name
  address_prefixes     = each.value.address_range
  virtual_network_name = azurerm_virtual_network.this.name

  dynamic "delegation" {
    for_each = lookup(each.value, "delegation", {}) != null ? [1] : []

    content {
      name = lookup(each.value.delegation, "name", null)

      service_delegation {
        name    = lookup(each.value.delegation.service_delegation, "name", null)
        actions = lookup(each.value.delegation.service_delegation, "actions", null)
      }
    }
  }
}

output "subnet_ids" {
  description = "Map of subnet names and IDs"
  value = {
    for k, v in azurerm_subnet.this : v.name => v.id
  }
}

Elsewhere, I create an App Service and associate it with a subnet:

resource "azurerm_app_service" "this" {
  name                = var.app_svc_name
  resource_group_name = var.rg_name
  location            = var.location
  #...
}

resource "azurerm_app_service_virtual_network_swift_connection" "this" {
  app_service_id = azurerm_app_service.this.id
  subnet_id      = lookup(module.networking.subnet_ids, var.app_svc_subnet_name, null)
}

This code works to create everything correctly. However, when I execute a destroy plan, Terraform fails and gives the error:

Error: Unsupported attribute
on main.tf line 396:

subnet_id      = lookup(module.networking.subnet_ids, var.app_svc_subnet_name, null)

module.networking is object with 2 attributes
This object does not have an attribute named “subnet_ids”.

Why does the destroy run have a problem with this code?

This does seem to me like it might be an actual bug in Terraform, so you may get a better response by opening a GitHub issue on the Terraform repo to report it.