Resource Groups, VNets & VMs
Provision a working Azure environment — resource group, network, and VM — in Terraform.
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.
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
} - Write the resource block for a resource group with a variable-driven location.
- Add a subnet that references the VNet’s name and resource group.
- Add an output exposing the subnet’s ID.
- Run
terraform planand read the dependency order Terraform chose.
Cheat Sheet▾
| Resource | Type |
|---|---|
| Resource group | azurerm_resource_group |
| Network | azurerm_virtual_network |
| Subnet | azurerm_subnet |
| NIC | azurerm_network_interface |
| VM | azurerm_linux_virtual_machine |
| Reference | azurerm_x.name.attr |
| Output | output "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.