Azurerm_subnet wont work with policy

If a Azure policy has “deny subnet with NSG” set in Azure Tenant\managmengroup, then the Terraform code “azurerm_subnet” wont work. Because there is no NSG parameter in the resource “azurerm_subnet” in Terraform.

I am using Terraform to deploy Azure vnet, subnets and NSG. If a Azure policy has “deny subnet with NSG” set in Azure Tenant\managmengroup, then the “azurerm_subnet” wont work. Because there is no NSG parameter in the resource “azurerm_subnet” in Terraform.

Recently in our organization, a new Azure security policy was applied “deny subnet with NSG”. This policy does not allow subnet to be created unless the NSG is linked to it at the time of creation. This is our security requirement to connect the subnet to an existing NSG when the the Subnet is created.

Due to this policy all of the existing Terraform code is broken.

Is there any way or option whereby I can link NSG at the Subnet Creation level. I do not want to revert the code to ARM template which will fix it.

My sample code looks like as below which uses azurerm_subnet_network_security_group_association:

#Create a new subnet
resource “azurerm_subnet” “test_subnets” {
count = length(var.totalsubnets)
name = lookup((var.csubnets[count.index]), “name”)
resource_group_name = azurerm_resource_group.our_rg.name
virtual_network_name = azurerm_virtual_network.our_vnet.name
address_prefixes = [lookup((var.our_subnets[count.index]), “address_prefix”)]
service_endpoints = var.service_endpoints
}

#Create a new nsg
resource “azurerm_network_security_group” “nsgs” {
count = length(var.our_subnets)
name = “{var.ourvnet["name"]}−nsg−{lookup((var.our_subnets[count.index]), “name”)}”
location = azurerm_resource_group.our_rg.location
resource_group_name = azurerm_resource_group.our_rg.name
}

Associate the NSG to the Subnet

resource “azurerm_subnet_network_security_group_association” “nsg_associations” {
count = length(var.our_subnets)
subnet_id = azurerm_subnet.our_subnets[count.index].id
network_security_group_id = azurerm_network_security_group.nsgs[count.index].id

depends_on = [azurerm_network_security_group.nsgs, azurerm_subnet.our_subnets]

}