Skip to content
8 min read Updated

Surviving Azure Policies: Zero-Trust Hub & Spoke with Terraform

Build an Azure Hub & Spoke network with Terraform that denies internet ingress from day one and survives DeployIfNotExists policies without breaking CI/CD.


Disclosure: This post contains Amazon affiliate links (marked with *). As an Amazon Associate I earn from qualifying purchases. Buying through them costs you nothing extra.

Your Terraform pipeline is green. The deployment completes without errors. You grab a coffee.

Ten minutes later, Azure Policy has rewritten three of your resources. You run terraform plan again. It detects drift and tries to revert. Policy blocks the revert with a cryptic permission error. Your pipeline is now stuck, and nobody touched the code.

In an enterprise Azure tenant, that is a normal Tuesday.

Below is a Hub & Spoke architecture hardened for that environment: Zero-Trust NSGs on every spoke subnet from the first apply, centralized Private DNS, and lifecycle rules that stop the policy drift loop.

Get the base Hub & Spoke template free on GitHub

The Two Things That Break Every Naive Deployment

Hub & Spoke is Microsoft’s reference topology for Azure networking. It centralizes traffic inspection, simplifies DNS management, and scales cleanly. What the whiteboard diagram doesn’t show is the governed tenant fighting your IaC at every step.

Two failure modes reliably break a standard Terraform deployment in a governed environment:

1. The DINE Death Loop
DeployIfNotExists and Modify policies act after your deployment: they stamp tags, force DNS zone links, enable Defender, whatever your security team decided to enforce tenant-wide. Terraform knows nothing about this. It sees the mutation as drift and plans a revert, which either hits a policy deny or gets undone at the next policy evaluation. The plan never converges and the pipeline stays red.

2. The Default-Allow Network
A freshly deployed Azure subnet without an NSG has no traffic filtering at all: outbound internet access and lateral movement between subnets are open. For an ISO 27001 or KRITIS audit, that is an immediate finding. The NSG has to be bound the moment the subnet exists, not in a follow-up ticket.

Spoke address space is easy to get wrong when it is spread across variables, so it is worth computing the ranges once up front. The IPv4 subnet calculator gives you the network, broadcast and usable host count for each prefix, which is exactly the set of numbers an auditor wants when they ask how many hosts a spoke can hold.

The fix is to make the Terraform code itself defensive against both.

Target Architecture

┌─────────────────────────────────────────────────────────┐
│                    Hub VNet                             │
│   ┌──────────────────────────────────────────────────┐  │
│   │  Private DNS Zones (centralized)                 │  │
│   │  privatelink.blob.core.windows.net               │  │
│   │  privatelink.database.windows.net                │  │
│   │  privatelink.vaultcore.azure.net                 │  │
│   │  privatelink.azurecr.io                          │  │
│   └──────────────────────────────────────────────────┘  │
└──────────────────────┬──────────────────────────────────┘
    VNet Peering (↔)            VNet Peering (↔)
┌─────────────────────┐       ┌──────────────────────────┐
│  Spoke 01 VNet      │       │  Spoke 02 VNet           │
│  ┌───────────────┐  │       │  ┌─────────────────────┐ │
│  │ snet-default  │  │       │  │ snet-default        │ │
│  │ + NSG (Deny)  │  │       │  │ + NSG (Deny)        │ │
│  └───────────────┘  │       │  └─────────────────────┘ │
└─────────────────────┘       └──────────────────────────┘
         ↑                                ↑
   BLOCKED by NSG                   BLOCKED by NSG
   (Internet → Deny)                (Internet → Deny)

Three engineering decisions drive this:

  • Zero-Trust NSGs, bound to Spoke subnets at creation
  • Centralized Private DNS: four PaaS zones in the Hub, shared by all Spokes
  • Defensive lifecycle blocks that let Terraform and Azure Policy coexist

Step 1: The Zero-Trust NSG Baseline

The most common mistake is creating an NSG and forgetting the subnet association. An NSG without a binding enforces nothing.

We create the rules and bind them in the same terraform apply:

resource "azurerm_network_security_group" "zero_trust" {
  name                = "nsg-zero-trust-${var.environment}"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name

  # Rule 1: Allow internal VNet-to-VNet traffic (via Peering)
  security_rule {
    name                       = "Allow-VNet-Inbound"
    priority                   = 100
    direction                  = "Inbound"
    access                     = "Allow"
    protocol                   = "*"
    source_port_range          = "*"
    destination_port_range     = "*"
    source_address_prefix      = "VirtualNetwork"
    destination_address_prefix = "VirtualNetwork"
  }

  # Rule 2: Explicit deny for all internet traffic
  security_rule {
    name                       = "Deny-Internet-Inbound"
    priority                   = 4096
    direction                  = "Inbound"
    access                     = "Deny"
    protocol                   = "*"
    source_port_range          = "*"
    destination_port_range     = "*"
    source_address_prefix      = "Internet"
    destination_address_prefix = "*"
  }
}

# The critical binding - no association, no enforcement
resource "azurerm_subnet_network_security_group_association" "spoke1_nsg_bind" {
  subnet_id                 = azurerm_subnet.spoke1_default.id
  network_security_group_id = azurerm_network_security_group.zero_trust.id
}

resource "azurerm_subnet_network_security_group_association" "spoke2_nsg_bind" {
  subnet_id                 = azurerm_subnet.spoke2_default.id
  network_security_group_id = azurerm_network_security_group.zero_trust.id
}

The priority gap between 100 and 4096 is intentional. It leaves room for thousands of application-specific rules without renumbering the baseline, so your security team can add rules for RDP, SSH, or application ports without touching the foundation.

Two things to be clear about. Azure’s built-in DenyAllInBound rule (priority 65500) already drops unsolicited internet ingress once an NSG is attached; the explicit 4096 deny makes that intent visible in code and in audit exports. And this baseline is inbound only. The default AllowInternetOutBound rule still lets workloads reach the internet. To block egress, add an outbound deny for the Internet service tag or force-tunnel 0.0.0.0/0 through a firewall in the Hub with a route table.

Step 2: Centralized Private DNS

When Spoke workloads use Private Endpoints, they need to resolve private IPs for PaaS services like Storage or Key Vault. Deploying a DNS zone in every Spoke is the wrong approach. It fragments your DNS and causes resolution conflicts the moment traffic crosses a peering boundary.

Centralize all zones in the Hub instead. Note that peering alone does not share DNS: a Private DNS zone only answers for VNets linked to it. Spokes resolve the zones either through their own VNet links to the Hub zones, or by pointing their custom DNS servers at a resolver in the Hub (Azure DNS Private Resolver or a forwarder VM). The snippet below creates the zones and links the Hub; add the Spoke links or the resolver before you deploy Private Endpoints in the Spokes.

variable "private_dns_zones" {
  type        = list(string)
  description = "Essential Azure PaaS Private Link DNS Zones"
  default = [
    "privatelink.blob.core.windows.net",
    "privatelink.database.windows.net",
    "privatelink.vaultcore.azure.net",
    "privatelink.azurecr.io"
  ]
}

resource "azurerm_private_dns_zone" "enterprise_zones" {
  for_each            = toset(var.private_dns_zones)
  name                = each.key
  resource_group_name = azurerm_resource_group.rg.name

  lifecycle {
    ignore_changes = [
      tags["hidden-title"],
      tags["CreatedByPolicy"]
    ]
  }
}

That lifecycle block needs an explanation.

Step 3: The DINE Bypass

This is the detail that separates a Terraform template that works in a demo from one that survives production.

When a DeployIfNotExists or Modify policy fires, it often writes metadata onto your resources, such as tags like CreatedByPolicy=True or hidden-title. Those are the two this tenant’s policies add; check which tags your own policies write. The tags mean nothing to your workload, but your governance team wants them there.

Terraform sees the injected tags as drift and plans to delete them. If a deny policy requires the tags, the deletion fails; if a Modify policy owns them, they come back at the next evaluation. Either way the same diff shows up on every run.

The lifecycle block creates a narrow exception:

lifecycle {
  ignore_changes = [
    tags["hidden-title"],
    tags["CreatedByPolicy"]
  ]
}

Terraform now ignores exactly these two tags and nothing else. The infrastructure stays fully managed by IaC, and the compliance tooling keeps its metadata.

The same protection applies to the VNet Links:

resource "azurerm_private_dns_zone_virtual_network_link" "hub_links" {
  for_each              = azurerm_private_dns_zone.enterprise_zones
  name                  = "link-to-hub-${each.value.name}"
  resource_group_name   = azurerm_resource_group.rg.name
  private_dns_zone_name = each.value.name
  virtual_network_id    = azurerm_virtual_network.hub.id

  lifecycle {
    ignore_changes = [tags]
  }
}

The VNet Links get a broader ignore_changes = [tags]. Policies targeting link resources tend to inject several tags at once, and listing them individually is not worth the maintenance overhead.

The Result

After terraform apply, you have a topology that holds up in a governed environment:

  • Isolated by default: no workload subnet exists without an NSG bound to it
  • DNS centralized: one set of Private DNS zones in the Hub instead of copies per Spoke
  • Pipeline-stable: policy-injected tags no longer show up as drift
  • Audit-friendly: a concrete starting point for the network controls in ISO 27001 Annex A.8 (A.8.20, A.8.22) and NIS2 Article 21

The Zero-Trust NSGs, centralized DNS, and DINE bypass logic from this article are packaged as a single module on GitHub, free and MIT licensed.

For the underlying networking concepts (peering, DNS, NSGs) rather than just the Terraform syntax, Netzwerke: Verstehen, Einrichten, Administrieren* is the reference I keep coming back to.

Was this helpful?
Share
DW

David Woitzik

Hybrid Cloud Engineer

I work mostly with Azure, Terraform, and Zero-Trust network design, and publish the Terraform templates and write-ups I wanted when I was solving the same problems.

Keep reading

More like this in your inbox

New Terraform modules and articles by email. No spam.