Getting Started with Terraform for Azure
What Is Terraform?
Terraform by HashiCorp is an open-source Infrastructure as Code tool that uses HCL (HashiCorp Configuration Language) to define and provision infrastructure across multiple cloud providers.
Setting Up for Azure
Install Terraform
# macOS
brew install terraform
# Windows (Chocolatey)
choco install terraform
# Linux
sudo apt-get install terraform
Authenticate to Azure
az login
az account set --subscription "your-subscription-id"
Your First Configuration
Create main.tf:
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~> 3.0"
}
}
required_version = ">= 1.0"
}
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "rg" {
name = "rg-demo"
location = "uksouth"
tags = {
environment = "dev"
managed_by = "terraform"
}
}
resource "azurerm_storage_account" "storage" {
name = "stdemo${random_string.suffix.result}"
resource_group_name = azurerm_resource_group.rg.name
location = azurerm_resource_group.rg.location
account_tier = "Standard"
account_replication_type = "LRS"
min_tls_version = "TLS1_2"
}
resource "random_string" "suffix" {
length = 6
special = false
upper = false
}
output "storage_account_name" {
value = azurerm_storage_account.storage.name
}
Core Workflow
terraform init # Download providers and initialise backend
terraform plan # Preview changes
terraform apply # Apply changes (with confirmation)
terraform destroy # Remove all managed resources
Variables
Define in variables.tf:
variable "location" {
type = string
default = "uksouth"
description = "The Azure region for resources"
}
variable "environment" {
type = string
description = "Environment name (dev, test, prod)"
validation {
condition = contains(["dev", "test", "prod"], var.environment)
error_message = "Environment must be dev, test, or prod."
}
}
Supply values via:
terraform.tfvarsfile-var="key=value"command lineTF_VAR_keyenvironment variables
State Management
Terraform tracks resources in a state file. For team use, store state remotely:
terraform {
backend "azurerm" {
resource_group_name = "rg-terraform-state"
storage_account_name = "stterraformstate"
container_name = "tfstate"
key = "demo.tfstate"
}
}
Best Practices
- Always use remote state for shared infrastructure
- Lock your provider versions to avoid unexpected changes
- Use
terraform planbefore every apply - Tag all resources for cost tracking and ownership
- Organise code into logical files:
main.tf,variables.tf,outputs.tf - Use modules for reusable infrastructure patterns