Skip to main content

VNet Terraform

Vamos criar uma VNet usando o Terraform

A ideia é separar todo o ambiente de redes em um único resource group e usar essa infraestrutura em outros cenários.

Estrutura do Projeto

O projeto será composto por arquivos .tf, que você pode organizar assim:

terraform/ ├── main.tf ├── variables.tf └── outputs.tf

provider "azurerm" {
features = {}
}

# Criar o Resource Group
resource "azurerm_resource_group" "rg" {
name = "myResourceGroup"
location = "East US"
}

# Criar a 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
}

# Subnet Pública
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"]
}

# Subnet Privada
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"]
}

# Subnet Interna
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"]
}

# Criar o Gateway para a Subnet Privada
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
}
}

# Criar o Gateway para a Subnet Interna
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
}
}