Error: creating Subnet Reasons: 'Subnets must have a Network Security Group.'

has anyone ran into an issue like this? if so how did you get past it? I tried deploying the same resources with bicep and it worked with no issues, so it seems to be a terraform thing in how the creation process works.

My company is working on moving to Azure landing zones and with that comes certain policies, one that is stopping us from being able to deploy to a specific subscription is “Subnets must have a Network Security Group” my code has subnets and NSG associations. The problem I am running into is that terraform is creating the subnets and then putting the association on the subnet, but the policy is stopping the deployment before the association can happen because it is seeing the subnet without an NSG. I can go in and add the subnet manually and select the NSG in the Azure portal, but that kind of defeats the IaC process. do you know of a way with code to attach the NSG at the time of subnet creation? this is a policy that will remain in place so find a way to make this work is a must for us.

Here is the full error

Error: creating Subnet (Subscription: “XXXX-XXXXX-XXXXXX-XXXXX-XXXX”
│ Resource Group Name: “example-resources”
│ Virtual Network Name: “example-network”
│ Subnet Name: “frontend”): performing CreateOrUpdate: unexpected status 403 (403 Forbidden) with error: RequestDisallowedByPolicy: Resource ‘frontend’ was disallowed by policy. Reasons: ‘Subnets must have a Network Security Group.’. See error details for policy resource IDs.

│ with azurerm_subnet.example,
│ on test.tf line 34, in resource “azurerm_subnet” “example”:
│ 34: resource “azurerm_subnet” “example” {

Thanks,

Jim

The newer version of azure caf landing zone archetype does not have this policy because of this issue. You can modify that policy to be in audit mode instead of deny mode. Besides that, you wouldn’t be able to create subnets since there’s no attribute for associating nsg to subnet during creation.