|
| 1 | + |
| 2 | + |
| 3 | +locals { |
| 4 | + resource_group_name = split("/", var.resource_group_id)[4] |
| 5 | + |
| 6 | + # Calculate VNet address space from subnet prefixes |
| 7 | + # 1. Collects all subnet address prefixes into a flat list |
| 8 | + # 2. Calculates the smallest possible CIDR block that can contain all subnets |
| 9 | + # 3. Uses this calculated CIDR as the VNet's address space |
| 10 | + all_subnet_prefixes = flatten([ |
| 11 | + for subnet in values(var.subnets) : subnet.address_prefixes |
| 12 | + ]) |
| 13 | + # Get the smallest network that contains all subnets |
| 14 | + vnet_cidr = [cidrhost( |
| 15 | + format("%s/%s", |
| 16 | + cidrhost(local.all_subnet_prefixes[0], 0), |
| 17 | + tonumber(split("/", local.all_subnet_prefixes[0])[1]) - 1 |
| 18 | + ), |
| 19 | + 0 |
| 20 | + )] |
| 21 | + |
| 22 | +} |
| 23 | + |
| 24 | +resource "azurerm_virtual_network" "vnet" { |
| 25 | + name = var.vnet_name |
| 26 | + location = var.location |
| 27 | + resource_group_name = local.resource_group_name |
| 28 | + address_space = local.vnet_cidr |
| 29 | + tags = var.tags |
| 30 | + |
| 31 | + lifecycle { |
| 32 | + create_before_destroy = true |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +resource "azurerm_subnet" "subnets" { |
| 37 | + for_each = var.subnets |
| 38 | + |
| 39 | + name = each.key |
| 40 | + resource_group_name = local.resource_group_name |
| 41 | + virtual_network_name = azurerm_virtual_network.vnet.name |
| 42 | + address_prefixes = each.value.address_prefixes |
| 43 | + service_endpoints = each.value.service_endpoints |
| 44 | + private_endpoint_network_policies_enabled = each.value.private_endpoint_network_policies_enabled |
| 45 | + private_link_service_network_policies_enabled = each.value.private_link_service_network_policies_enabled |
| 46 | + |
| 47 | + dynamic "delegation" { |
| 48 | + for_each = each.value.delegate |
| 49 | + content { |
| 50 | + name = delegation.value.name |
| 51 | + service_delegation { |
| 52 | + name = delegation.value.service |
| 53 | + actions = delegation.value.actions |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | +} |
| 58 | + |
0 commit comments