Resource Groups, VNets & VMs

💤0
Lv 10 XP
← ☁️ Microsoft Azure · Terraform with Azure

Resource Groups, VNets & VMs

Intermediate ⭐ 80 XP ⏱ 20 min #azure#terraform#vm#vnet

Provision a working Azure environment — resource group, network, and VM — in Terraform.

📖Theory

Azure resources in Terraform follow a dependency chain. A typical VM needs, in order: a resource group, a virtual network and subnet, a network interface, and finally the VM itself. Terraform infers most of the order from implicit dependencies — when one resource references another’s attribute, it builds them in the right sequence.

You parameterize with variables, expose results with outputs, and keep related resources in modules. The whole environment becomes reproducible code you can review, version, and destroy cleanly.

🌍Real-World Example
resource "azurerm_resource_group" "main" {
  name     = "rg-demo"
  location = "westeurope"
}

resource "azurerm_virtual_network" "main" {
  name                = "vnet-demo"
  address_space       = ["10.0.0.0/16"]
  location            = azurerm_resource_group.main.location
  resource_group_name = azurerm_resource_group.main.name
}

resource "azurerm_subnet" "web" {
  name                 = "web"
  resource_group_name  = azurerm_resource_group.main.name
  virtual_network_name = azurerm_virtual_network.main.name
  address_prefixes     = ["10.0.1.0/24"]
}

output "vnet_id" {
  value = azurerm_virtual_network.main.id
}
✍️Hands-On Exercise
  1. Write the resource block for a resource group with a variable-driven location.
  2. Add a subnet that references the VNet’s name and resource group.
  3. Add an output exposing the subnet’s ID.
  4. Run terraform plan and read the dependency order Terraform chose.
🧾Cheat Sheet
ResourceType
Resource groupazurerm_resource_group
Networkazurerm_virtual_network
Subnetazurerm_subnet
NICazurerm_network_interface
VMazurerm_linux_virtual_machine
Referenceazurerm_x.name.attr
Outputoutput "x" { value = … }
💬Common Interview Questions
How does Terraform know the order to create resources?

It builds a dependency graph from references — when one resource uses another’s attribute, Terraform creates the dependency first. You rarely specify order manually.

Why reference attributes instead of hardcoding names?

References create the dependency edges Terraform needs and keep a single source of truth, so renaming or changing a value propagates correctly everywhere.

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type