Go to content
Infrastructure

Designing Stable Terraform Module Interfaces Across Environments

Terraform modules are reusable packages of infrastructure configuration. A module is a folder of .tf files that declares resources such as a database, a load balancer, or a Kubernetes cluster. It exposes input variables (settings callers pass in) and outputs (values callers read back). When the same module is used for dev, staging, and production, the module’s interface (its input variables and outputs) is the contract all three environments share. A stable interface lets you make a change for one environment (a new feature, a different instance size, a stricter security setting) without forcing changes to the other environments’ call sites (the module blocks that instantiate it).

The design goal is to express environment differences as values passed into the module, not as structural changes to the module itself. Group related settings into objects with defaults, validate inputs at the call site, keep provider-specific details inside the module, and treat outputs as a contract you do not break casually. The sections that follow start with a module interface that becomes hard to maintain, walk through its redesign, and then cover the mechanisms that keep an interface stable across environments. By the end, you will be able to look at a module’s variables.tf and outputs.tf and predict whether the interface will survive the next environment-specific requirement.

What Makes a Module Interface Stable Across Environments

A module’s input variables are its API, and they deserve the same care as a REST API endpoint. Every variable name, type, default, and validation rule is part of the contract every caller depends on. Adding a required input breaks every call site. Removing or renaming an output breaks every consumer. Adding an optional input with a default, or adding a new output, does not. That asymmetry is the foundation of interface stability: make new capabilities optional, with defaults, so existing callers keep working.

Scope is the other foundation. A well-scoped module represents one logical resource group, can be described in one sentence, and has 5 to 15 input variables and creates 2 to 10 resources. A module that needs many more variables than that should be split into smaller modules. A module that creates an entire environment (VPC plus compute plus database plus cache) is too tightly coupled to reuse safely, and a module that creates a single tag is too granular to be worth calling.

Stability across environments adds one more requirement: the module must not encode environment policy. If the module branches on the environment name, changing staging policy means editing the module, which affects dev and prod too. Environment differences belong in the values callers pass, not in conditionals inside the module.

A Database Module That Becomes Hard to Maintain

Consider a database module that accumulates features over a few months. It starts with instance size and engine version, then gains replica, autoscaling, backup, and encryption flags. It also requires the caller to supply the network layout.

# modules/database/variables.tf

variable "environment" {
  type = string
}

variable "instance_class" {
  type = string
}

variable "engine_version" {
  type = any
}

variable "enable_replica" {
  type    = bool
  default = false
}

variable "enable_autoscaling" {
  type    = bool
  default = false
}

variable "enable_backup" {
  type    = bool
  default = false
}

variable "enable_encryption" {
  type    = bool
  default = false
}

variable "subnet_ids" {
  type = list(string)
}

variable "security_group_ids" {
  type = list(string)
}
# modules/database/main.tf

resource "aws_db_subnet_group" "main" {
  name       = "${var.environment}-database-subnets"
  subnet_ids = var.subnet_ids
}

resource "aws_db_instance" "main" {
  identifier              = "${var.environment}-database"
  instance_class          = var.instance_class
  engine_version          = var.engine_version
  multi_az                = var.environment == "prod" ? true : false
  storage_encrypted       = var.enable_encryption
  backup_retention_period = var.enable_backup ? 30 : 0
  db_subnet_group_name    = aws_db_subnet_group.main.name
  vpc_security_group_ids  = var.security_group_ids
}

resource "aws_db_instance" "replica" {
  count               = var.enable_replica ? 1 : 0
  replicate_source_db = aws_db_instance.main.identifier
  instance_class      = var.instance_class
}
# modules/database/outputs.tf

output "endpoint" {
  value = aws_db_instance.main.endpoint
}

output "password" {
  value = aws_db_instance.main.password
}

The prod call site passes every flag:

module "database" {
  source = "../modules/database"

  environment        = "prod"
  instance_class     = "db.r6g.xlarge"
  engine_version     = "15.4"
  enable_replica     = true
  enable_autoscaling = true
  enable_backup      = true
  enable_encryption  = true
  subnet_ids         = module.vpc.database_subnet_ids
  security_group_ids = [module.security_group.id]
}

This interface breaks down in several ways.

The boolean flags are the first problem. Each feature gets its own switch, so deletion protection requires adding enable_deletion_protection and updating every environment’s call site. The interface grows wider, and callers have to read all six flags to know what the module creates. Grouping related settings, or using a preset such as an environment tier, avoids this sprawl.

The environment conditionals are worse, because multi_az = var.environment == "prod" puts environment policy inside the module. When staging needs multi-AZ, someone edits the module, and the change ripples through dev and prod. The module now has to know about every environment that uses it, and every environment inherits every policy change.

The interface also leaks provider-specific details. Callers must know that instance_class is an AWS RDS instance class, and they must supply subnet_ids and security_group_ids in AWS’s networking vocabulary. A module shaped this way cannot serve a GCP or Azure caller without rework.

Two smaller defects make the problem worse. engine_version is typed any, which disables type checking for a value the module passes straight to the provider; a caller can pass a number and get a confusing provider error instead of a clear message at the call site. And the module has no validation, so prod can be deployed with no replica, no backup, and no encryption, and Terraform accepts it. The mistake shows up later, in production.

The outputs add a security problem: password is emitted without sensitive = true, so it appears in plain text in plan output and in state.

Redesigning the Interface Around Objects and Defaults

The fix is to group related settings into a typed object and give every optional field a default. Terraform 1.3 added the optional modifier for object type attributes. optional(string, "default") means the caller may omit the attribute, and the module receives "default". Without a default, an omitted attribute is null; with a non-null default, the attribute is guaranteed never to be null in the receiving module. Defaults apply top-down in nested object types: outer defaults first, then nested defaults.

# modules/database/variables.tf

variable "database" {
  description = "Database configuration shared by all environments."
  type = object({
    tier                  = string
    engine                = string
    engine_version        = string
    instance_class        = string
    database_name         = string
    username              = string
    encryption            = optional(bool, true)
    replicas              = optional(number, 0)
    autoscaling = optional(object({
      enabled      = optional(bool, false)
      max_capacity = optional(number, 0)
    }), { enabled = false, max_capacity = 0 })
  })

  validation {
    condition     = var.database.replicas >= 0
    error_message = "Replicas cannot be negative."
  }

  validation {
    condition     = var.database.engine_version != "latest"
    error_message = "Pin engine_version to a specific release, not \"latest\"."
  }

  validation {
    condition     = var.database.tier != "prod" || (var.database.replicas >= 2 && var.database.autoscaling.enabled)
    error_message = "Production databases require at least 2 replicas with autoscaling enabled."
  }
}

variable "network" {
  description = "Network dependencies created by the caller."
  type = object({
    subnet_ids         = list(string)
    security_group_ids = list(string)
  })
}

Dev passes only the required fields:

module "database" {
  source = "../../modules/database"

  database = {
    tier           = "dev"
    engine         = "postgres"
    engine_version = "15.4"
    instance_class = "db.t3.micro"
    database_name  = "app"
    username       = "app"
  }

  network = {
    subnet_ids         = module.vpc.database_subnet_ids
    security_group_ids = [module.security_group.id]
  }
}

Prod overrides only what differs:

module "database" {
  source = "../../modules/database"

  database = {
    tier           = "prod"
    engine         = "postgres"
    engine_version = "15.4"
    instance_class = "db.r6g.xlarge"
    database_name  = "app"
    username       = "app"
    replicas       = 2
    autoscaling = {
      enabled      = true
      max_capacity = 8
    }
  }

  network = {
    subnet_ids         = module.vpc.database_subnet_ids
    security_group_ids = [module.security_group.id]
  }
}

Dev gets encryption, zero replicas, and no autoscaling from the defaults. Prod sets replicas and autoscaling explicitly. Adding a new optional attribute with a default does not break either call site, which is the stability mechanism in action.

The tier field exists so validation can enforce environment-specific rules. The caller supplies explicit settings for every environment, so the module never branches on tier to change behavior. If dev and prod share an AWS account, include the environment in the database_name you pass, for example app-prod, because the module should not invent a naming convention.

# modules/database/main.tf

resource "aws_db_subnet_group" "main" {
  name       = var.database.database_name
  subnet_ids = var.network.subnet_ids
}

resource "aws_db_instance" "main" {
  identifier              = var.database.database_name
  instance_class          = var.database.instance_class
  engine                  = var.database.engine
  engine_version          = var.database.engine_version
  storage_encrypted       = var.database.encryption
  db_subnet_group_name    = aws_db_subnet_group.main.name
  vpc_security_group_ids  = var.network.security_group_ids
}

resource "aws_db_instance" "replica" {
  count               = var.database.replicas
  replicate_source_db = aws_db_instance.main.identifier
  instance_class      = var.database.instance_class
}

The module maps the generic object to AWS resources internally, including the autoscaling policy resources that the autoscaling block controls. Names carry meaning too.

Validation Catches Bad Configuration at the Call Site

A variable declaration can include zero or more validation blocks, each with a condition and an error_message. The condition is evaluated after automatic conversion to the declared type, and it can refer only to the variable being validated. If the condition returns false, Terraform returns an error at the module call site using the text in error_message, so the prod root module gets a message that says exactly what is wrong while the dev root module is unaffected.

A rule that compares replicas to the environment name cannot reference a separate environment variable, because the condition can only see its own variable. The environment marker has to live inside the same object, which is why the redesigned interface puts tier in the database object. Keeping the rule in the module means every environment that uses the module gets the same protection, and the rule travels with the module when another project adopts it.

The prod rule in the redesign, at least 2 replicas with autoscaling enabled, fails during terraform plan in the prod root module, not weeks later in production. The same mechanism rejects engine_version = "latest" and forces callers to pin a specific release. Validation can also check nested object fields such as replica counts, ports, and image tags, and it can require explicit container image tags that match semantic versions or commit hashes. Conditions can use Terraform’s built-in functions, so checks like contains, length, and regex are available.

Type constraints are still enforced when a variable has validation blocks. A caller passing replicas = "two" gets a type error before validation runs, because Terraform converts the value to the declared type first. Write the exact type the module expects, and use type any only when the module passes the value to another system without accessing its contents.

Outputs Are a Contract Too

Outputs are the module’s API return values. Every consumer that reads module.database.endpoint depends on that name and shape. Output the values callers need to reference from other modules, such as the resource id, ARN, and connection endpoint, and only output values consumers actually need.

Adding an output is backward compatible. Removing an output, renaming it, or changing its type breaks every consumer. Prefer stable semantic shapes over raw provider attribute references. The redesigned module outputs endpoint as an object with host and port rather than the raw aws_db_instance.endpoint string, so the module can change the underlying resource without changing the contract.

# modules/database/outputs.tf

output "endpoint" {
  description = "Host and port of the primary database."
  value = {
    host = aws_db_instance.main.address
    port = aws_db_instance.main.port
  }
}

output "database_name" {
  value = aws_db_instance.main.db_name
}

output "username" {
  value = aws_db_instance.main.username
}

output "replica_endpoints" {
  value = aws_db_instance.replica[*].address
}

output "master_password" {
  value     = aws_db_instance.main.password
  sensitive = true
}

Secrets need explicit handling. Mark any output that contains a password or key with sensitive = true so Terraform hides it from plan output. If the caller supplies the secret as an input, do not output it at all; the module should not echo secrets back. Sensitive values are still stored in state in plain text, so decide deliberately whether to output a secret at all.

Keep Provider-Specific Details Inside the Module

The module’s interface should not force callers to know which provider implements it. The first step is dependency inversion: modules should receive dependencies from the root module rather than embedding their own copies, so they do not know or care how those dependencies were obtained. The network variable in the redesign is the example. The caller passes subnet and security group IDs whether they come from a VPC module, a data source (a Terraform construct that reads existing infrastructure instead of creating it), or a hardcoded list. The module does not create or look up the network.

The same principle covers existence checks. Rather than writing a module that detects whether an object exists and creates it if not, make the module accept the object as an input and let the caller decide whether to create it inline or retrieve it from a data source.

Multi-cloud reuse is possible but bounded. Terraform intentionally does not abstract over similar services from different vendors, but modules can create lightweight multi-cloud abstractions by defining object types for common concepts and swapping implementations. The tradeoff is the lowest common denominator: the generic object can only carry features every target provider supports. instance_class is still an AWS-shaped string; a provider-neutral interface would need a size concept the module maps to each provider’s instance type naming.

Provider configuration has its own constraint. A provider alias is a named extra configuration of a provider, used when infrastructure spans multiple accounts or regions. Passing aliases to modules that use count, for_each, or depends_on is not supported and produces the error "Providers cannot be configured within modules using count, for_each or depends_on." This Terraform issue documents the failure. If a module needs multiple provider configurations, structure the call so the root module passes them, and test the combination before relying on it.

Version constraints are part of the contract too. Declare required Terraform and provider versions in the module’s terraform block, using >= for the minimum version, for example required_version = ">= 1.3" and an AWS provider constraint of >= 5.0. For reusable modules, let the root module manage the maximum provider version; root modules can add upper bounds. Do not hardcode resource names, IDs, or other values that limit reuse across environments or accounts; parameterize values that may vary.

Separate Backends for Separate Environments

Named workspaces are not a suitable way to isolate staging from production. Use reusable modules instead, and give each environment a separate configuration with its own backend. Each environment directory has its own root module that instantiates the shared modules and passes environment-specific values, and each environment has its own state backend, the storage location for Terraform’s record of the resources it manages, and its own credentials.

environments/
  dev/
    main.tf
    backend.tf
  staging/
    main.tf
    backend.tf
  prod/
    main.tf
    backend.tf
modules/
  database/
  network/

All three directories use the same module interface and differ only in the values they pass. When the module adds an optional attribute with a default, dev and staging keep working without changes, and prod can adopt the new setting when ready. Shared resources that span environments can be referenced through remote state: one environment’s configuration reads another environment’s outputs from its state file.

A backend shared across environments creates security and data integrity risks, especially when state contains sensitive values. Keep each environment’s state and credentials separate, and leave the module unaware of which environment it is running in.

More in Infrastructure Back to top ↑