How to create a subnet with NSG for an existing VNet?

In my Azure landing zone, my organization has established a policy that will not let me create a subnet without NSG.

Use case: I want to create an additional subnet for an existing VNet. How can I do that?

I tried the following: I have captured the existing VNet using data block:

data "azurerm_virtual_network" "aks" {
  name                = data.azurerm_resources.vnets.resources[0].name
  resource_group_name = azurerm_kubernetes_cluster.default.node_resource_group
}

Then I have tried to create a subnet:

resource "azurerm_subnet" "example" {
  name                 = "example-subnet"
  resource_group_name  = azurerm_kubernetes_cluster.default.node_resource_group
  virtual_network_name = data.azurerm_virtual_network.aks.name
  address_prefixes     = ["10.0.1.0/24"]
}

This gives me an error message that it is not allowed to create a subnet without NSG. But as per Terraform Registry, I do not see how to refer to an NSG in the creation of my subnet. How can I solve this problem?

Please note:

  1. Yes, I know that I can configure a new VNet with subnet(s) with NSG using this syntax:
resource "azurerm_virtual_network" "default" {
  name                = "${var.projectName}-${var.clusterName}-vnet"
  address_space       = ["10.240.0.0/12"]
  location            = azurerm_resource_group.default.location
  resource_group_name = azurerm_resource_group.default.name
  subnet {
          address_prefix = "10.240.0.0/16"
          name           = "ag"
          security_group = azurerm_network_security_group.default.id
  }
}

But this does not help me, because I have to operate on an existing VNet.

  1. Yes, I know that I can assign an NSG to an existing subnet via azurerm_subnet_network_security_group_association. But this will also try to create the subnet first which will also fail because of the missing NSG.

What can I do?

Thanks a lot!

Best regards,
Thomas

Hello,
Did you find a solution for this?
I have the same problem as you.

What’s blocking you in creating a subnet without an NSG, is it Azure Policy enforcing the policy?

You can’t do this as they are created as separate resources so it must be exempt from the policy and instead mandate using a module that has the subnet and NSG resources.

You can have the policy in audit mode instead of deny to show where this hasn’t been followed but basically this breaks TF deployment.