Terraform with Azure: Complete Module Development

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

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

Using `for_each` for Subnets

# 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.

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.