VNet
Last updated: December 15, 2024Virtual Network (VNet) allows you to create your private networks in Azure. You can create an Azure VNet using the following snippet:
resource "azurerm_virtual_network" "vnet" {
name = "${local.resource_prefix}_vnet"
location = local.location
resource_group_name = azurerm_resource_group.rg.name
address_space = ["10.0.0.0/16"]
depends_on = [
azurerm_resource_group.rg
]
}
This will create VNet with the address space "10.10.0.0/16" with two subnet samples. The location of the VNet is the same as of the resource group it is in.
VNet with multiple address spaces
If you need further address spaces, you can add them to the address_space array. Example:
resource "azurerm_virtual_network" "vnet" {
name = "${local.resource_prefix}_vnet"
location = local.location
resource_group_name = azurerm_resource_group.rg.name
address_space = ["10.0.0.0/16"]
depends_on = [
azurerm_resource_group.rg
]
}Virtual Network Peering
Sometimes you need to enable communication between two virtual networks. This is done by peering these two networks together.
In the example below, assuming you have created two vnets one with name "vnet-hub" and one with "vnet-spoke", you can peer these two vnets together with the code below:
resource "azurerm_virtual_network_peering" "hub-to-spoke" {
name = "hub-to-spoke"
resource_group_name = azurerm_resource_group.rg.name
virtual_network_name = azurerm_virtual_network.vnet-hub.name
remote_virtual_network_id = azurerm_virtual_network.vnet-spoke.id
allow_forwarded_traffic = true
allow_gateway_transit = true
allow_virtual_network_access = true
use_remote_gateways = false
depends_on = [
azurerm_virtual_network.vnet-hub,
azurerm_virtual_network.vnet-spoke
]
}
resource "azurerm_virtual_network_peering" "spoke-to-hub" {
name = "spoke-to-hub"
resource_group_name = azurerm_resource_group.rg.name
virtual_network_name = azurerm_virtual_network.vnet-spoke.name
remote_virtual_network_id = azurerm_virtual_network.vnet-hub.id
allow_forwarded_traffic = false
allow_gateway_transit = false
allow_virtual_network_access = true
use_remote_gateways = false
depends_on = [
azurerm_virtual_network.vnet-hub,
azurerm_virtual_network.vnet-spoke
]
}Further reading