VNet Terraform
Let's create a VNet using Terraform
The idea is to separate the entire network environment into a single resource group and use this infrastructure in other scenarios.
Project Structure​
The project will be composed of .tf files, which you can organize like this:
terraform/ ├── main.tf ├── variables.tf └── outputs.tf
provider "azurerm" {
features = {}
}
# Create the Resource Group
resource "azurerm_resource_group" "rg" {
name = "myResourceGroup"
location = "East US"
}
# Create the VNet
resource "azurerm_virtual_network" "vnet" {
name = "myVnet"
address_space = ["10.0.0.0/16"]
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
}
# Public Subnet
resource "azurerm_subnet" "public_subnet" {
name = "public-subnet"
resource_group_name = azurerm_resource_group.rg.name
virtual_network_name = azurerm_virtual_network.vnet.name
address_prefixes = ["10.0.1.0/24"]
service_endpoints = ["Microsoft.Storage"]
}
# Private Subnet
resource "azurerm_subnet" "private_subnet" {
name = "private-subnet"
resource_group_name = azurerm_resource_group.rg.name
virtual_network_name = azurerm_virtual_network.vnet.name
address_prefixes = ["10.0.2.0/20"]
service_endpoints = ["Microsoft.Storage"]
}
# Internal Subnet
resource "azurerm_subnet" "internal_subnet" {
name = "internal-subnet"
resource_group_name = azurerm_resource_group.rg.name
virtual_network_name = azurerm_virtual_network.vnet.name
address_prefixes = ["10.0.3.0/24"]
service_endpoints = ["Microsoft.Storage"]
}
# Create the Gateway for the Private Subnet
resource "azurerm_public_ip" "private_ip" {
name = "private-gateway-ip"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
allocation_method = "Dynamic"
}
resource "azurerm_virtual_network_gateway" "private_gateway" {
name = "private-gateway"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
type = "Vpn"
vpn_type = "RouteBased"
ip_configuration {
name = "vnetGatewayConfig"
public_ip_address_id = azurerm_public_ip.private_ip.id
private_ip_address_allocation = "Dynamic"
subnet_id = azurerm_subnet.private_subnet.id
}
sku {
name = "Basic"
tier = "Basic"
capacity = 2
}
}
# Create the Gateway for the Internal Subnet
resource "azurerm_public_ip" "internal_ip" {
name = "internal-gateway-ip"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
allocation_method = "Dynamic"
}
resource "azurerm_virtual_network_gateway" "internal_gateway" {
name = "internal-gateway"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
type = "Vpn"
vpn_type = "RouteBased"
ip_configuration {
name = "vnetGatewayConfig"
public_ip_address_id = azurerm_public_ip.internal_ip.id
private_ip_address_allocation = "Dynamic"
subnet_id = azurerm_subnet.internal_subnet.id
}
sku {
name = "Basic"
tier = "Basic"
capacity = 2
}
}