Terraform

Terraform Modules on Azure: Creating, Versioning, and Composing HCL

Intermediate
15 minutes
Updated October 2026

Hands-on guide to authoring reusable Azure Terraform modules (azurerm) from scratch — input validation rules, flat root-module composition, semantic Git tag pinning, and zero-downtime refactoring with moved blocks.

Table of Contents

What Is a Module

A module is a directory of .tf files used together. Every Terraform config has a root module; anything you call with module blocks is a child module.

Modules exist to:

  • Reuse the same pattern everywhere (e.g., "a standard web app")
  • Encapsulate complexity — callers set 5 variables, not 50 resources
  • Enforce standards — tagging, naming, security baked in

Module Structure

modules/
└── web-app/
    ├── main.tf        # resources
    ├── variables.tf   # inputs
    ├── outputs.tf     # outputs
    ├── versions.tf    # provider constraints
    └── README.md      # usage docs

No magic: modules are plain .tf files in a folder.

Building Your First Module

modules/resource-group/main.tf

resource "azurerm_resource_group" "this" {
  name     = "${var.name}-${var.environment}"
  location = var.location

  tags = merge(var.tags, {
    Environment = var.environment
    ManagedBy   = "Terraform"
  })
}

modules/resource-group/variables.tf

variable "name" {
  description = "Base name for the resource group"
  type        = string

  validation {
    condition     = can(regex("^[a-z0-9-]+$", var.name))
    error_message = "Name must be lowercase alphanumeric with hyphens."
  }
}

variable "environment" {
  description = "Environment: dev, staging, or prod"
  type        = string

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Environment must be dev, staging, or prod."
  }
}

variable "location" {
  description = "Azure region"
  type        = string
  default     = "uksouth"
}

variable "tags" {
  description = "Additional resource tags"
  type        = map(string)
  default     = {}
}

modules/resource-group/outputs.tf

output "name" {
  description = "Resource group name"
  value       = azurerm_resource_group.this.name
}

output "id" {
  description = "Resource group ID"
  value       = azurerm_resource_group.this.id
}

output "location" {
  value = azurerm_resource_group.this.location
}

modules/resource-group/versions.tf

terraform {
  required_version = ">= 1.6"

  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 4.0"
    }
  }
}

Calling Modules

Local Path

module "rg_dev" {
  source = "./modules/resource-group"

  name        = "payments"
  environment = "dev"
  location    = "uksouth"

  tags = {
    Team = "Payments"
  }
}

module "rg_prod" {
  source = "./modules/resource-group"

  name        = "payments"
  environment = "prod"
}

Git Source (Shared Modules)

module "rg" {
  source = "git::https://github.com/myorg/tf-modules.git//resource-group?ref=v1.2.0"

  name        = "payments"
  environment = "prod"
}

The ?ref= pins a git tag — always pin versions for shared modules.

Terraform Registry

module "vnet" {
  source  = "Azure/vnet/azurerm"
  version = "4.1.0"

  vnet_name           = "prod-vnet"
  resource_group_name = module.rg_prod.name
  address_space       = ["10.0.0.0/16"]
}

Versioning with Git

# Tag releases semantically
git tag v1.0.0
git push --tags

# Callers pin:
# source = "git::https://...//module?ref=v1.0.0"

Upgrade path: bump the tag, update ref= in caller, terraform init -upgrade, terraform plan.

Module Best Practices

1. Keep the Interface Small

# Bad — exposes everything, brittle
variable "node_count" {}
variable "vm_size" {}
variable "os_disk_type" {}
# ... 40 more variables

# Good — opinionated defaults, few knobs
variable "size" {
  type    = string
  default = "medium"   # maps internally to real settings
}

2. Validate Inputs

variable "cidr" {
  type = string
  validation {
    condition     = can(cidrhost(var.cidr, 0))
    error_message = "Must be a valid CIDR block."
  }
}

3. Compose Modules, Don't Nest Deeply

root
├── module.network
├── module.aks  (takes network outputs)
└── module.app  (takes aks outputs)

Deeply nested modules are painful to debug. Prefer flat composition at the root.

4. Document with README + Examples

# Usage

module "rg" {
  source      = "./modules/resource-group"
  name        = "app"
  environment = "prod"
}

5. Output What Callers Need

IDs and names other modules will consume — not every attribute.

Wiring Modules Together

Modules compose through outputs and inputs — the root module is where they meet:

module "network" {
  source      = "./modules/network"
  environment = var.environment
  cidr        = "10.0.0.0/16"
}

module "database" {
  source            = "./modules/database"
  environment       = var.environment
  subnet_id         = module.network.db_subnet_id      # output → input
  allowed_cidr      = module.network.app_subnet_cidr
}

module "app" {
  source      = "./modules/app"
  environment = var.environment
  db_host     = module.database.endpoint
  subnet_ids  = module.network.app_subnet_ids
}

This is the "flat composition" pattern: each module declares what it needs, the root wires them. The dependency graph is readable at a glance, and module.database.endpoint failing to resolve is a plan-time error — not a 2 AM discovery.

The alternative — modules reaching into each other's internals via data sources or remote state — couples them to implementation details that make refactoring painful. Outputs are the contract; keep it that way.

Common Mistakes

Count/for_each at module level changing index

# Dangerous — removing an item destroys others by index shift
module "vms" {
  count = length(var.vm_names)
  name  = var.vm_names[count.index]
}

# Better — keyed by name
module "vms" {
  for_each = toset(var.vm_names)
  name     = each.key
}

Provider blocks inside modules

# Inside a module — DON'T do this
provider "azurerm" {
  alias = "east"
}

Pass providers from the root instead:

module "east" {
  source = "./modules/app"
  providers = {
    azurerm = azurerm.east
  }
}

Relative path hell

source = "../../../../../modules/vnet" breaks when files move. Prefer a registry or git source for anything shared beyond one repo.

Testing Modules

# Validate standalone
cd modules/resource-group
terraform init
terraform validate

# Test with a fixture
mkdir test && cat > test/main.tf <<EOF
module "test" {
  source      = "../"
  name        = "test"
  environment = "dev"
}
EOF
cd test && terraform init && terraform plan

Upgrading Modules Safely

A module change rolls out to every caller — treat upgrades like API changes:

  1. Bump the version — v1.1.0 for new features, v2.0.0 for breaking changes (renamed variables, changed defaults)
  2. Update one caller — start with dev, run terraform init -upgrade && terraform plan
  3. Review the plan carefully — a "harmless" module change can show Plan: 0 to add, 0 to change, 47 to destroy if defaults shifted
  4. Roll out gradually — staging next, prod last; don't bump every environment in one commit
  5. Keep a changelog — CHANGELOG.md per module repo so callers know what changed before they upgrade

The moved block (Terraform 1.1+) helps when a module refactor renames resources internally — declare the old→new mapping in the module so callers upgrade without resource recreation:

# inside the module, after renaming aws_s3_bucket.old to aws_s3_bucket.new
moved {
  from = aws_s3_bucket.old
  to   = aws_s3_bucket.new
}

Without moved, a rename in the module = destroy + recreate for every caller. With it, the state address updates silently — one of Terraform's least-known, highest-value features for module authors.

Written & Reviewed by Yasir Masood, CloudOpsGuide Editor

Our tutorials and troubleshooting runbooks are written by a DevOps practitioner with hands-on experience operating Kubernetes, Terraform, CI/CD pipelines, and Linux infrastructure in production. Commands, manifests, and configurations are verified against current tooling releases. Learn more about our editorial process or report a correction or outdated flag.

More Terraform Guides

View all in Terraform →
Beginner · 14 minutes
Terraform 101: Managing AWS Infrastructure as Code
Clicking through the AWS console works until it doesn't — nobody remembers what they clicked, environments drift apart, and "it works in staging" becomes a meme. Terraform fixes this by making infrastructure code: you describe what you want in HCL (HashiCorp Configuration Language), and Terraform makes the cloud match it. This guide follows the official HashiCorp AWS get-started path — install → write configuration → init → apply → change → destroy — so by the end you'll have provisioned and torn down a real EC2 instance.
Read guide
Intermediate · 10 minutes
Terraform AWS Modules: Production AWS in 20 Lines of HCL
Writing raw Terraform for AWS works — until you need a VPC with public and private subnets across three availability zones, NAT gateways, route tables, and flow logs. That's easily 500 lines of HCL and a week of testing. The terraform-aws-modules organization on GitHub exists because everyone kept writing that same 500 lines. It's a community collection of 60+ battle-tested modules covering VPC, EKS, RDS, IAM, Lambda, ECS, S3, and more — each maintained, versioned, and documented. This tutorial shows how to use them properly, from the registry to a working production-shaped network.
Read guide
Beginner · 12 minutes
Terraform Azure Service Principal: Authentication Guide
Create and configure Azure Service Principals for Terraform authentication with step-by-step instructions.
Read guide