Terraform 41: A reusable module for names + tags
easy⏱ 5 mincourseterraform
A module is a reusable folder of .tf
A module is just a directory with variables.tf, main.tf, and outputs.tf. Callers pass inputs and consume outputs; the internals are encapsulated. This is how you stamp out the same shape across dev/uat/prod without copy-paste.
# modules/naming/variables.tf
variable "environment" { type = string }
variable "service" { type = string }
variable "extra_tags" { type = map(string), default = {} }
Standardized names + merged tags
Compute names in a locals block so the convention lives in one place, and merge() a base tag set with caller overrides. Every downstream resource references local.tags and the local.names.* — never an ad-hoc string.
# modules/naming/main.tf
locals {
names = {
rg = "${var.environment}-${var.service}-rg"
key_vault = "${var.service}-kv-${var.environment}"
sb_namespace = "${var.environment}-${var.service}-namespace"
}
tags = merge({
ManagedBy = "terraform"
Environment = var.environment
Service = var.service
}, var.extra_tags)
}
Expose the results as outputs
Outputs are the module's public API. Callers read module.naming.rg_name and module.naming.tags — they never reach into the module's internals. That contract is what makes the module swappable and testable.
# modules/naming/outputs.tf
output "rg_name" { value = local.names.rg }
output "kv_name" { value = local.names.key_vault }
output "sb_namespace" { value = local.names.sb_namespace }
output "tags" { value = local.tags }
Pin the convention, ban the one-off
The whole point is that a resource name like prod-orders-rg can only be produced one way. If someone needs a name, they call the module — no hand-typed strings that drift between environments and break automation that greps on the pattern.
Build the standardized name
Implement resourceName(env, service, type) returning `${env}-${service}-${type}`, lowercased. Log resourceName("prod", "orders", "rg") — it must print prod-orders-rg. Bonus asserted: uppercase inputs are normalized ("PROD" -> prod).