I have the below code, please pay attention to the “azurerm_network_security_group.example” resource block where I have declared the NSG name as a variable. The first pass of deployment is completed with default values and now I am passing a different NSG name as variable input for the next deployment. My understanding is that TF will destroy the existing NSG which has old name also automatically de-associate the nsg from the subnet. But it is not the case once I run the command and getting an error that NSG can’t be deleted as it is already associated with the Subnet. Could you please help me how this can be resolved . thanks.
Here is the error
azurerm_network_security_group.example: Destroying... [id=/subscriptions/7fbdc229-f0b8-4d8f-829d-7d6488df93b1/resourceGroups/myNewResourceGroupName/providers/Microsoft.Network/networkSecurityGroups/testnsg]
╷
│ Error: deleting Network Security Group "testnsg" (Resource Group "myNewResourceGroupName"): network.SecurityGroupsClient#Delete: Failure sending request: StatusCode=0 -- Original Error: Code="InUseNetworkSecurityGroupCannotBeDeleted" Message="Network security group /subscriptions/7fbdc229-f0b8-4d8f-829d-7d6488df93b1/resourceGroups/myNewResourceGroupName/providers/Microsoft.Network/networkSecurityGroups/testnsg cannot be deleted because it is in use by the following resources: /subscriptions/7fbdc229-f0b8-4d8f-829d-7d6488df93b1/resourceGroups/myNewResourceGroupName/providers/Microsoft.Network/virtualNetworks/tftestvnet1/subnets/tfsubnet1. In order to delete the Network security group, remove the association with the resource(s). To learn how to do this, see aka.ms/deletensg." Details=[]
│
main.tf
# Configure the Azure provider
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~> 2.65"
}
}
required_version = ">= 0.14.9"
}
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "rg" {
name = var.resource_group_name
location = "EastUS"
tags = {
environment = "Production"
team = "azuredevops"
}
}
resource "azurerm_virtual_network" "tftestnetwork" {
name = "tftestvnet1"
resource_group_name = azurerm_resource_group.rg.name
address_space = ["10.0.0.0/16"]
location = azurerm_resource_group.rg.location
subnet {
address_prefix = "10.0.0.0/24"
name = "tfsubnet1"
security_group = azurerm_network_security_group.example.id
}
tags = {
environment = "Production"
team = "azuredevops"
}
}
resource "azurerm_network_security_group" "example" {
name = var.nsgname
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
tags = {
environment = "Production"
team = "azuredevops"
}
}
variables section
variable "resource_group_name" {
default = "myTFResourceGroup"
}
variable "nsgname" {
default = "testnsgfromvaraible"
}