Terraform with Azure: Complete Module Development

On this page

Modules are the building blocks of reusable Terraform infrastructure. A good module encapsulates complexity and enforces company standards (naming conventions, tagging, security). This guide builds an Azure VNET module with subnets and security groups.

Directory Structure

Code6 lines
/modules
  /networking
    main.tf       # Resources
    variables.tf  # Inputs
    outputs.tf    # Outputs to other modules
    versions.tf   # Provider constraints

Using `for_each` for Subnets

HCL21 lines
# variables.tf
variable "subnets" {
  type = map(object({
    address_prefix = string
  }))
}

# main.tf
resource "azurerm_virtual_network" "vnet" {
  name = var.vnet_name
  # ...
}

resource "azurerm_subnet" "subnet" {
  for_each = var.subnets
  
  name                 = each.key
  resource_group_name  = var.resource_group_name
  virtual_network_name = azurerm_virtual_network.vnet.name
  address_prefixes     = [each.value.address_prefix]
}

Key Takeaways

  • Keep modules focused and single-responsibility.
  • Always define `terraform` block with version constraints.
  • Pin module versions in the consumption code.

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

Subscribe to get the latest posts sent to your email.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

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.