Terraform Basics: Infrastructure as Code for Azure

I’ve been managing Azure resources with ARM templates for years. They work, but they’re verbose and hard to read. Terraform is a breath of fresh air. Here’s how to get started.

Why Terraform?

  • Readable: HCL is much cleaner than JSON/ARM
  • Multi-cloud: Same tool for Azure, AWS, GCP
  • State management: Tracks what’s deployed
  • Plan before apply: See changes before making them

Installation

# Windows (chocolatey)
choco install terraform

# Verify
terraform version

Your First Configuration

# main.tf
provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "example" {
  name     = "rg-terraform-demo"
  location = "West Europe"
  
  tags = {
    environment = "dev"
    managed_by  = "terraform"
  }
}

resource "azurerm_storage_account" "example" {
  name                     = "stterraformdemo"
  resource_group_name      = azurerm_resource_group.example.name
  location                 = azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

The Workflow

# Initialize (downloads providers)
terraform init

# See what will change
terraform plan

# Apply changes
terraform apply

# Destroy everything
terraform destroy

Variables

# variables.tf
variable "environment" {
  type        = string
  description = "Environment name"
  default     = "dev"
}

variable "location" {
  type    = string
  default = "West Europe"
}

# main.tf
resource "azurerm_resource_group" "example" {
  name     = "rg-${var.environment}"
  location = var.location
}

State Management

By default, state is stored locally. For teams, use remote state:

terraform {
  backend "azurerm" {
    resource_group_name  = "rg-terraform-state"
    storage_account_name = "stterraformstate"
    container_name       = "tfstate"
    key                  = "prod.terraform.tfstate"
  }
}

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.