Skip to content

Reusable private network foundation

Level: Intermediate

Overview and purpose

Build a VNet, named subnets, deny-all-inbound NSG, and an explicit NSG association for every subnet.

Prerequisites and dependencies

Offline tests mock AzureRM. Live use requires an existing group, approved address ranges, region availability, and the Azure foundation root.

Inputs and outputs

subnets maps stable names to CIDRs. CIDR syntax is validated, but overlap/containment still need design review and Azure validation.

Source and usage

Read main.tf and the focused tests. Use this directory as the working directory for the commands below. Azure modules are child modules: use examples/03-azure-foundation as the live deployment entry point rather than applying a module without its caller.

Validation and optional execution

The commands use Bash syntax (Azure Cloud Shell supports it). Plan-only tests never create Azure resources; Azure tests use mock_provider. init may download provider plugins from the Terraform Registry. For Azure live commands, authenticate, select the intended subscription, and set ARM_SUBSCRIPTION_ID and your own STORAGE_ACCOUNT_NAME first. No live Azure apply/destroy is part of CI.

terraform init -backend=false
terraform validate
terraform test

Inspect every plan before apply. A saved plan is sensitive and can contain values from configuration/state; do not commit or publish it.

Expected results and verification

The plan contains the VNet, NSG, requested subnets, and one association per subnet. All inbound traffic is denied by default, including traffic from the same VNet.

Read terraform output and the plan's resource addresses. A mocked assertion only checks configuration behavior, not provider APIs, credentials, cost, regional availability, or application runtime behavior.

Cleanup

For local data examples, terraform destroy removes the exercise's managed records. For Azure, use the root configuration's reviewed destroy plan with the same state, credentials, and input values. Confirm the resources are gone. Do not delete the state file as a substitute for destroying resources.

After confirming destruction, delete ignored local .terraform/, plan, and state files if you no longer need them. Keep committed provider lock files. Shared or retained resources may need separate approved cleanup.

Cost, security, and limitations

VNet/NSG objects have no direct compute charges, but workloads and networking services can. This module does not configure outbound NAT, gateways, DNS, or approved workload allow rules.

These are educational examples, not certified production modules. For additional Azure services, use the companion AzureTerraformTemplates library after reviewing its individual prerequisites, provider constraints, and security settings.

Complete Terraform source

modules/azure-network/main.tf
terraform {
  required_version = ">= 1.7, < 2.0"
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = ">= 5.14.0, < 6.0"
    }
  }
}

variable "name" {
  description = "Virtual network name; also prefixes the security group."
  type        = string
}

variable "resource_group_name" {
  description = "Existing resource group name."
  type        = string
}

variable "location" {
  description = "Azure region for the network resources."
  type        = string
}

variable "address_space" {
  description = "Non-overlapping VNet CIDR blocks."
  type        = list(string)
  default     = ["10.30.0.0/16"]
}

variable "subnets" {
  description = "Stable subnet names mapped to CIDRs inside the VNet."
  type        = map(string)
  default     = { workload = "10.30.1.0/24" }

  validation {
    condition     = length(var.subnets) > 0 && alltrue([for prefix in values(var.subnets) : can(cidrhost(prefix, 0))])
    error_message = "Supply at least one valid CIDR prefix."
  }
}

resource "azurerm_virtual_network" "this" {
  name                = var.name
  location            = var.location
  resource_group_name = var.resource_group_name
  address_space       = var.address_space
}

resource "azurerm_network_security_group" "this" {
  name                = "${var.name}-nsg"
  location            = var.location
  resource_group_name = var.resource_group_name

  security_rule {
    name                       = "DenyAllInbound"
    priority                   = 4096
    direction                  = "Inbound"
    access                     = "Deny"
    protocol                   = "*"
    source_port_range          = "*"
    destination_port_range     = "*"
    source_address_prefix      = "*"
    destination_address_prefix = "*"
  }
}

resource "azurerm_subnet" "this" {
  for_each             = var.subnets
  name                 = each.key
  resource_group_name  = var.resource_group_name
  virtual_network_name = azurerm_virtual_network.this.name
  address_prefixes     = [each.value]
}

resource "azurerm_subnet_network_security_group_association" "this" {
  for_each                  = azurerm_subnet.this
  subnet_id                 = each.value.id
  network_security_group_id = azurerm_network_security_group.this.id
}

output "id" {
  description = "Virtual network resource ID."
  value       = azurerm_virtual_network.this.id
}

output "subnet_ids" {
  description = "Map of subnet names to resource IDs."
  value       = { for name, subnet in azurerm_subnet.this : name => subnet.id }
}