name: module-patterns
description: Terraform module development patterns and best practices. Provides structure, versioning, and output scaffolds. Use when creating reusable modules.
Module Patterns
Terraform module development patterns and conventions.
variable "project" {
description = "Project name used in resource naming"
type = string
validation {
condition = can(regex("^[a-z][a-z0-9-]*$", var.project))
error_message = "Project name must start with a letter and contain only lowercase letters, numbers, and hyphens."
}
}
variable "environment" {
description = "Environment name (dev, staging, prod)"
type = string
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Environment must be dev, staging, or prod."
}
}
Optional with Default
variable "instance_type" {
description = "EC2 instance type for compute resources"
type = string
default = "t3.medium"
}
variable "enable_encryption" {
description = "Enable encryption at rest for all supported resources"
type = bool
default = true
}
Complex Type with Defaults
variable "node_groups" {
description = "Map of EKS managed node group definitions"
type = map(object({
instance_types = list(string)
min_size = number
max_size = number
desired_size = number
disk_size = optional(number, 100)
disk_type = optional(string, "gp3")
capacity_type = optional(string, "ON_DEMAND")
labels = optional(map(string), {})
taints = optional(list(object({
key = string
value = string
effect = string
})), [])
}))
default = {}
}
Sensitive Variable
variable "database_password" {
description = "Database master password"
type = string
sensitive = true
validation {
condition = length(var.database_password) >= 16
error_message = "Database password must be at least 16 characters."
}
}
Tags Variable
variable "tags" {
description = "Additional tags to apply to all resources"
type = map(string)
default = {}
}
outputs.tf Patterns
Resource Identifiers
output "id" {
description = "The ID of the primary resource"
value = aws_resource.this.id
}
output "arn" {
description = "The ARN of the primary resource"
value = aws_resource.this.arn
}
Connection Information
output "endpoint" {
description = "Endpoint for connecting to the resource"
value = aws_resource.this.endpoint
}
output "security_group_id" {
description = "ID of the associated security group"
value = aws_security_group.this.id
}
# moves.tf - Use when renaming resources
moved {
from = aws_instance.web
to = aws_instance.application
}
moved {
from = aws_s3_bucket.data
to = module.storage.aws_s3_bucket.main
}
moved {
from = module.old_name
to = module.new_name
}