"In production, copy-pasting Terraform code is a liability. Modularizing it is a strategy."
As your cloud infrastructure grows, managing it as clean, consistent, and secure code becomes essential. Thatβs where Terraform modules come in.
Letβs explore how to build reusable and secure Terraform modules for production-grade Azure environments.
π€ Why Use Modules?
Terraform modules help you:
- Avoid duplication
- Enforce standards (naming, tagging, access policies)
- Separate concerns (network, storage, compute)
- Improve reusability across environments (dev/stage/prod)
π Recommended Module Structure
terraform-azure-storage-account/
β
βββ main.tf
βββ variables.tf
βββ outputs.tf
βββ locals.tf
βββ README.md
β Best Practices for Reusability
-
Prefix resource names with variables (e.g.,
var.env
) - Use locals for derived values
- Tag everything (cost, ownership, environment)
- Provide defaults for non-sensitive inputs
- Version your modules (via Git or registry)
π Best Practices for Security
- Never hardcode secrets (use
azurerm_key_vault_secret
) - Always enable diagnostic settings and logging
- Apply least-privilege roles (via role assignments)
- Use HTTPS-only, encryption, and private endpoints when applicable
π¦ Sample Module: Azure Storage Account
main.tf
resource "azurerm_storage_account" "this" {
name = var.name
resource_group_name = var.resource_group_name
location = var.location
account_tier = var.tier
account_replication_type = var.replication_type
tags = merge(var.tags, {
module = "storage-account"
})
}
variables.tf
variable "name" {}
variable "resource_group_name" {}
variable "location" {}
variable "tier" {
default = "Standard"
}
variable "replication_type" {
default = "LRS"
}
variable "tags" {
default = {}
}
π₯ Consuming the Module
module "storage" {
source = "git::https://github.com/your-org/terraform-azure-storage-account.git?ref=v1.0.0"
name = "mystorageacc01"
resource_group_name = "prod-rg"
location = "westeurope"
tags = {
env = "prod"
owner = "infra-team"
}
}
π GitHub Module Repo: terraform-azure-storage-account
π Bonus Tips
- Use
terraform-docs
to auto-generateREADME.md
- Pin provider versions to avoid drift
- Validate with
terraform validate
andtflint
π§ Final Thoughts
Reusable modules are your IaC power tools β they keep your cloud secure, clean, and maintainable at scale.
In the next post, weβll build a complete Azure network module with diagnostics, UDR, and firewall integration.
Follow for more insights on DevOps, IaC, and production-grade infrastructure design.
Top comments (2)
pretty cool tbh, been burned by copy paste mess before - you think most people hit these best practices because they learn the hard way, or something else keeps them on track?
Some comments may only be visible to logged-in visitors. Sign in to view all comments.