Back to Terraform

Design Modules Around Capabilities and Clear Contracts

November 5, 2026 Wasil Zafar 30 min read

Extract reusable infrastructure with typed inputs, useful outputs and explicit ownership

Table of Contents

  1. Extract a Capability, Not Every Single Resource
  2. Define Inputs That Express User Decisions
  3. Use Outputs to Connect Modules
  4. Keep Provider Configuration in the Calling Root
  5. Document Examples, Constraints and Destruction Behavior
  6. Refactor the Web Service into a Composable Module

Extract a Capability, Not Every Single Resource

A module is a directory of configuration that Terraform treats as one reusable unit. The directory you run commands in is the root module; each directory it calls with a module block is a child module. Deciding what belongs inside is the hard part.

One module per resource is not reuse

A team wraps aws_s3_bucket in modules/bucket, forwards fourteen arguments, returns the attributes it received and calls that reuse. The result is a second place to update for every provider change and a README that restates the provider documentation with fewer guarantees. The wrapper decided nothing, so it earned no boundary.

A module boundary should hold a capability: something a person would name, own, page someone about, and destroy as a unit. "The web service behind the load balancer" is a capability. "The bucket" is a resource with a folder around it.

Four questions decide whether a set of resources has earned a module:

QuestionTestExample
NameDoes the phrase already appear in a design review or an on-call rotation?A service module then matches how the team talks.
ChangeDoes one ordinary change touch most of the resources inside?A port change moves the listener, the target group and the security-group rules together.
ContractCan you state the inputs and outputs on one page without naming a resource type?A caller asks for "a service with two instances", not for a target-group attachment.
LifecycleAre they created and destroyed together?If destroying the module leaves half a working system, the boundary is wrong.

An organization-specific abstraction is not a thin wrapper, and usually worth building. It encodes decisions the organization already made: approved instance families, a mandatory tag set, a naming convention, a TLS policy. The distinction is direction. A wrapper forwards every provider option; an abstraction removes options and supplies the organization's answer. If the input list grows with every provider feature, you have a shadow API, not an abstraction.

Depth is the other failure. Each layer between root and resource should add exactly one decision; root, platform module, service module, resource is already three boundaries. Past that, inputs are plumbed through three variable blocks, outputs are re-exported three times, and errors name the innermost block instead of the caller's argument. Ask what decision a layer makes that its parent could not; "it groups files" is not an answer.

Two boundaries are worth avoiding. A module per environment forks the configuration, so a fix is applied twice and the copies drift; environments belong in separate roots. And a module whose only job is to add count around one resource moves that address without changing what it does.

Figure 1 is the path I use before creating a module directory. Figure 2 contrasts a forwarding chain with a capability. The difference is whether the boundary holds a decision the caller should not make.

Extract a Capability, Not Every Single Resource
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Resources sitting in one root"] --> B{"Would a product team
name this as one capability?"} B -- "no" --> B1["Leave it in the root
no module needed yet"] B -- "yes" --> C{"Do the resources change
together and share a lifecycle?"} C -- "no" --> C1["Split the capability
or keep the wiring in the root"] C -- "yes" --> D{"Does the boundary add a decision
the provider does not make?"} D -- "no" --> D1["Thin wrapper
delete it and call the resource"] D -- "yes" --> E{"Can a caller use it
without reading the body?"} E -- "no" --> E1["Contract is not ready
inputs or outputs still leak"] E -- "yes" --> F["Publish the module
README, example root, version"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class A,C,E primary; class B,D secondary; class F ok; class B1,C1 warn; class D1,E1 danger;
A capability boundary compared with a forwarding wrapper A root module on the left passes four inputs across a dashed capability boundary into a web-service module. Inside the boundary, security groups, a load balancer and counted instances are implementation detail. The module returns three outputs, and the provider credentials stay in the root. One boundary, one decision root module providers and backend state key module wiring capability boundary: web-service in: service = { name, instance_count, port, tags } vpc_id subnet_ids allowed_cidr security groups alb and web rules here load balancer listener + TG health check instances count from the input spread subnets out: endpoint target_group_arn instance_ids AWS API credentials live in the root, never in the module Same module, two roots: the capability travels, the wiring stays with the caller. Everything inside the dashed line is free to change without a caller edit.

Define Inputs That Express User Decisions

The interface is its variables and outputs, and the previous level treated those as a typed contract. Here the question is narrower: which values deserve to be inputs at all.

Start from decisions, not resources. For each candidate, ask who would set it and what they would decide. Three answers remove most of them: a value derived from another input belongs in a local; a value fixed by organizational policy belongs in a local or constant; a provider argument the caller has no opinion about should be the module's choice. What remains is what the caller knows and the module cannot: the service name, the instance count, the network, the owner.

Group by noun, not by resource. Attributes that always change together and describe one thing become a typed object; independent decisions supplied by different owners stay separate.

variable "service" {
  type = object({
    name           = string
    instance_count = number
    instance_type  = optional(string, "t3.micro")
  })
}

variable "vpc_id" {
  type = string
}
terraform fmt -check
terraform validate

A record and a neighbour are different things. service is a record: the caller thinks about the service as a unit, and a partial object is usually a mistake. vpc_id comes from a network owner at a different time, so folding it into the object would force that owner to read the service schema.

Default the common case, never the identity. A default instance type is a kindness; a default service name is a defect, because two callers who forget it silently collide. An optional attribute with a default fills the value during conversion, so the body never handles null; a bare optional attribute is right only when null signals something.

Validate meaning the type cannot. A type cannot say a count must be whole, or that two subnets are needed for availability. Those are validation blocks, and their messages are part of the interface: "subnet_ids must contain at least two subnets so the load balancer can span availability zones" tells the caller what to change.

Keep the surface minimal. Every variable is a promise to document, test and carry through every caller's diff. If a variable exists only to be forwarded to one resource argument, ask whether the caller should decide it at all. Sometimes yes — instance_type is a real cost decision — but ask.

Three patterns to ban in a shared module. Each one hides a failure that a caller will meet later:

Anti-patternWhat failsUse instead
type = anyEvery mismatch is postponed to the first expression that uses the value, so the error names your line instead of the caller's argument.A concrete object type, or a narrower type per input.
Boolean bundlesenable_alb and enable_https multiply into combinations no validation can describe.One enum input that rejects impossible states by construction.
Whole resource objectsUnstable across provider versions, full of null computed attributes and unreadable as a contract.A small object of the fields the caller actually decides.

Name the variable for the domain, not the module. Use name, not web_service_name, because the call site already names the module it belongs to. Set nullable to false on the top-level object so an explicit null fails at the call site. Put rules that span two variables in a check block or precondition, because a validation block sees only its own variable.

The experiment builds the contract before any AWS resource exists, using terraform_data as a stand-in so the exercise runs offline.

Configuration

Define Inputs That Express User Decisions

Execution status: design-only. Complete for Terraform CLI 1.17.1. The body uses only terraform_data, so no provider is downloaded and nothing billable is created; no run is recorded.

Prerequisites. Terraform CLI 1.17.1, a shell and an empty directory. No account or credentials.

Create modules/service/versions.tf and variables.tf. The version block pins the CLI only; there is no provider yet:

terraform {
  required_version = ">= 1.9.0"
}

variable "service" {
  description = "One deployable HTTP service: identity, size, listener and ownership."
  type = object({
    name           = string
    instance_count = number
    instance_type  = optional(string, "t3.micro")
    port           = optional(number, 80)
    health_path    = optional(string, "/healthz")
    tags           = optional(map(string), {})
  })
  nullable = false

  validation {
    condition     = can(regex("^[a-z][a-z0-9-]{2,24}$", var.service.name))
    error_message = "service.name must be 3 to 25 characters of lowercase letters, digits and hyphens, starting with a letter, for example \"orders-api\"."
  }

  validation {
    condition     = var.service.instance_count >= 1 && var.service.instance_count <= 6 && floor(var.service.instance_count) == var.service.instance_count
    error_message = "service.instance_count must be a whole number from 1 to 6. Use a second module call instead of one oversized service."
  }

  validation {
    condition     = startswith(var.service.health_path, "/")
    error_message = "service.health_path must be an absolute path beginning with \"/\", for example \"/healthz\"."
  }
}

variable "vpc_id" {
  description = "VPC that owns the service. Supplied by the caller, never looked up here."
  type        = string
}

variable "subnet_ids" {
  description = "Subnets for the instances, spread in order. At least two."
  type        = list(string)

  validation {
    condition     = length(var.subnet_ids) >= 2
    error_message = "subnet_ids must contain at least two subnets so instances can be spread across availability zones."
  }
}

variable "allowed_cidr" {
  description = "Single CIDR allowed to reach the listener, for example the operator address as /32."
  type        = string

  validation {
    condition     = can(cidrhost(var.allowed_cidr, 0))
    error_message = "allowed_cidr must be valid CIDR notation, for example \"203.0.113.10/32\"."
  }
}

Add main.tf and outputs.tf. The locals hold the derived decisions; the caller never supplies a name prefix or a merged tag map:

locals {
  name = "p07-${var.service.name}"
  tags = merge(var.service.tags, { managed-by = "terraform" })
}

resource "terraform_data" "this" {
  count = var.service.instance_count

  input = {
    name          = local.name
    instance_type = var.service.instance_type
    port          = var.service.port
    path          = var.service.health_path
    vpc           = var.vpc_id
    subnet        = var.subnet_ids[count.index % length(var.subnet_ids)]
  }
}

output "endpoint" {
  description = "Host name and port the caller should call once the service is live."
  value       = "http://${local.name}:${var.service.port}"
}

output "instance_ids" {
  description = "Instance identifiers in input order; index 0 is the first instance."
  value       = terraform_data.this[*].id
}

Call it twice from the root with placeholder network identifiers:

module "orders" {
  source = "./modules/service"

  service = {
    name           = "orders-api"
    instance_count = 2
    tags           = { owner = "payments" }
  }

  vpc_id       = "vpc-0123456789abcdef0"
  subnet_ids   = ["subnet-0aaa", "subnet-0bbb"]
  allowed_cidr = "203.0.113.10/32"
}

module "search" {
  source = "./modules/service"

  service = {
    name           = "search-api"
    instance_count = 1
    port           = 8080
  }

  vpc_id       = "vpc-0123456789abcdef0"
  subnet_ids   = ["subnet-0aaa", "subnet-0bbb"]
  allowed_cidr = "203.0.113.10/32"
}
  1. Run terraform init -input=false and terraform validate. Expect success with no provider downloaded.
  2. Run terraform plan. Expect two module instances and three terraform_data objects, with no cloud calls.
  3. Set instance_count = 0, then to the decimal 1.5, planning each time. Expect the range message twice; the second value passes the number type and fails your rule, which is why the rule exists.
  4. Set subnet_ids = ["subnet-0aaa"], then allowed_cidr = "203.0.113.10". Expect the two-subnet and CIDR messages.
  5. Add an owner attribute to the search call that the object does not declare, and plan. Expect no error and no effect: the extra attribute is discarded. Apply, then run terraform state list to see the resulting addresses.

Expected observation. Every failure is reported against the module call before any resource is planned, and each message names the rule and a legal example. The silently discarded attribute is the one behaviour a type cannot catch.

Failure checks. Each symptom points at one missing rule:

  • instance_count = 0 plans: the range rule is missing or inverted.
  • validate demands a provider: the body still contains an AWS resource.
  • The state list shows a terraform_data.this address with no module. prefix: the resource is in the root.

Cost and cleanup. Zero. No provider, no cloud object, local state only. Delete the directory.

Define Inputs That Express User Decisions
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Caller writes a module block"] --> B["Type conversion against
the declared object"] B -- "wrong shape or type" --> X1["Error at the call site
before any provider call"] B -- "undeclared attribute" --> W1["Silently discarded
declare it or rename it"] B --> C{"Explicit null?"} C -- "yes" --> X2["Error: required variable is null"] C -- "no" --> D["optional() defaults filled
during conversion"] D --> E{"Validation rules"} E -- "fail" --> X3["Error naming variable,
rule and example"] E -- "depends on unknown" --> W2["Deferred to apply
plan cannot decide"] E -- "pass" --> F["Typed value reaches locals"] F --> G["Resources and outputs"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class A,F,G primary; class B,C,D,E secondary; class X1,X2,X3 danger; class W1,W2 warn;

Figure 3 orders the checks Terraform applies.

Two branches are not errors

An undeclared attribute disappears without a warning, and a rule that depends on a value Terraform learns only during apply is deferred, so a clean plan is not proof that every rule will pass.

Use Outputs to Connect Modules

Inputs are what a module accepts; outputs are what it hands back. Between them they form a graph, and the graph is why modules compose. When one call references another's output, Terraform records an edge:

module "service" {
  source = "./modules/web-service"

  vpc_id     = module.network.vpc_id
  subnet_ids = module.network.subnet_ids
}

A reference does more than copy a string. It says the network must be created first, that a network change may affect the service, and that a destroy happens in reverse. No depends_on is needed; adding one would hide the reason.

Dependency injection means the caller supplies what the module needs. The alternative, a module that fetches its own dependencies, looks convenient and ages badly. Its usual form is a terraform_remote_state data source inside the module. The previous article covered the permission cost; the design cost is separate.

  • The dependency is invisible at the call site. Nothing in the module block says which network or account it binds to.
  • The module cannot be tested in isolation. Every example root needs the producer's state.
  • It serves one instance of that dependency. Two services in two networks need two module copies.
  • Failure arrives late, when the producer renames an output.

There is a defensible middle path. If a platform team publishes through remote state, do the lookup once in the root and pass the values down as ordinary inputs. The module stays injectable, and the coupling sits in one file you can review.

Return identifiers and endpoints, not resource objects. A load-balancer object exposes dozens of attributes, several unknown until apply, and the set changes between provider versions. Return what a consumer needs to connect — endpoint, target group ARN, instance ids — and name it for the consumer's vocabulary, because renaming an output is a breaking change for every caller.

When several values always travel together, return one object rather than five outputs:

output "network" {
  description = "Identifiers a workload needs to join this network."
  value = {
    vpc_id          = aws_vpc.this.id
    subnet_ids      = aws_subnet.private[*].id
    route_table_ids = aws_route_table.private[*].id
  }
}

The caller takes one edge and one variable. Adding a field is compatible; removing or renaming one is not. Do not aggregate unrelated values into an everything output, or every consumer depends on every change.

Figure 4 shows the difference in shape. On the left, the root wires two modules with a value reference and the edge is visible in the plan. On the right, the module reads a state snapshot itself, and a second root that wants a different network has no way to say so.

Dependency injection through outputs compared with a hidden remote-state read The left panel shows a root module passing module.network outputs into module.service, which creates a visible graph edge. The right panel shows a module reading the producer state snapshot directly, so a second root is bound to the same network and the dependency is invisible at the call site. Wired by the root root module: reads outputs, passes them down module.network exports vpc_id module.service never looks up vpc_id The reference is a graph edge, so create and destroy order are derived. One root shows the whole wiring. The module works in any network. Hidden lookup in the module producer state snapshot all of it, not one output needs GetObject on the key module.service reads at plan time second root same VPC, no choice Both consumers are bound to what the producer applied. Nothing at either call site says so. Inject the value once in the root, then the same module runs in any network, account or test. Prefer values over depends_on: the graph should learn the dependency from what you passed.

Keep Provider Configuration in the Calling Root

A module does not own its credentials, region or account. Those belong to the environment the caller is operating in, and the caller is a root module.

Child modules inherit the root's provider configuration. Since Terraform 0.13, a module with no provider block uses whatever the root declared, including its region, assume-role setting, default tags and any account guardrail. That is why one module can deploy the same service to a sandbox and a production account without a code change.

A module declares requirements, not configuration. It names the provider source and a version range in a required_providers block, which states requirements without configuring or installing anything. Terraform intersects every constraint in the tree, selects one version per provider and records it with its checksums in the lock file.

A second, differently configured provider needs an alias. The module declares which alias it expects; the caller supplies both configurations in the module block. Forgetting one fails with "Provider configuration not present", naming the module path before any resource is planned:

# modules/web-service/versions.tf
terraform {
  required_providers {
    aws = {
      source                = "hashicorp/aws"
      version               = ">= 6.0, < 7.0"
      configuration_aliases = [aws.replica]
    }
  }
}

# root module
module "web" {
  source = "./modules/web-service"

  providers = {
    aws         = aws
    aws.replica = aws.replica
  }
}
terraform init
terraform validate

A module must never own the provider

A module with its own provider block and a hardcoded region ignores the caller's intent. It cannot be used twice in one configuration, and it breaks the inheritance that makes one module work in sandbox and production. Declare requirements; let the root configure.

Two limits follow. Provider configurations cannot be created dynamically, so aliases cannot come from a for_each; a multi-region fan-out needs explicit module blocks. And default_tags belongs in the root provider, because it applies to every taggable resource in every module. Modules should still merge service-specific tags over the defaults, so cost attribution does not require patching them.

A resource-level region is not provider configuration. A module may accept that argument; it must not choose the provider's region for the caller.

Document Examples, Constraints and Destruction Behavior

A module is a product with a support surface, and the README is that surface. If a caller has to read main.tf to use the module, the contract is unfinished.

A useful README answers, in order: what capability it provides and does not provide; a copyable minimal example; requirements, meaning Terraform and provider ranges plus prerequisites such as an existing VPC with DNS support; generated input and output tables; constraints and non-goals; destruction behavior; and support, meaning the owner and how deprecations are announced.

The inputs table should carry the decision each input expresses, so a reader can tell instance_type (a cost decision) from subnet_ids (a decision made elsewhere). The outputs table should say what a consumer does with each value. Hand-written tables drift; generating them in CI turns documentation into a check.

Examples are tests. An examples/basic directory that calls the module through a relative source is a root module, so an init with no backend, a validate and a plan against a sandbox can run in CI. A complete variant exercises the optional attributes. Examples also surface interface bugs, because an example is the first caller who is not the author.

Constraints and non-goals belong in the README. State the region and availability-zone assumptions, the quota the module depends on, the permissions the caller needs, and the naming limits that shaped the code. Then state the non-goals: "does not create DNS records", "does not request certificates", "expects an existing VPC with two subnets". A non-goal prevents a fork, because the reader learns their requirement belongs in their own root.

Destruction behavior is part of the contract. A caller who runs terraform destroy should know the result beforehand. Document what the module removes, what the provider removes asynchronously, and what survives because something else owns it. The load balancer, listener, target group, attachments, instances and security groups go with the module. A log group with retention, an EBS snapshot, an S3 bucket with objects, a KMS key in its deletion window and a DNS record in a zone managed elsewhere may not.

Some resources must refuse to die

prevent_destroy turns an accidental destroy into a plan-time error, and the README should say which resources carry it. Resources whose deletion fails on non-empty storage need an explicit, documented force_destroy decision. Neither replaces a backup; both make the failure legible.

Finally, publish the support commitment: an owner, how consumers hear about changes, and what counts as breaking. In practice the interface is versioned, deprecations are announced in a changelog and kept for at least one major release, and an address change ships with a moved block rather than a message in a chat channel. The next part turns that promise into releases and constraints.

Figure 5 puts the contract and the destroy outcome side by side, because the second is the half readers skip.

The README contract and what survives a module destroy On the left, a README lists capability, inputs and outputs, constraints, support and destruction behavior. On the right, a destroy removes instances, the load balancer, listener, target group and security groups, while log retention, snapshots, object storage, a KMS key and records in another zone survive. Two halves of one contract README 1. capability, in one sentence and what it does not do 2. inputs and outputs, with the decision each one encodes 3. constraints and non-goals versions, quota, permissions 4. support, owner, changelog and what counts as breaking 5. destruction behavior what survives, what blocks terraform destroy, or removing the module call removed with the module instances and their disks load balancer and listener target group and attachments security groups survives destroy log group and its retention EBS snapshot S3 objects, unless forced KMS key, pending deletion DNS record in another zone EIP held by another owner Document each one, or the next team learns it live. The README says which column a resource lands in. prevent_destroy and a safe force_destroy default are decisions, not features to be discovered during an incident. A caller who has read only the README should be able to predict a destroy.

Refactor the Web Service into a Composable Module

The P07 web service is small, complete and already one root. It has nine addresses: two security groups, two instances, a load balancer, a target group, two attachments and a listener.

The refactor moves the capability and leaves the wiring. The root keeps its provider configuration, backend and VPC lookups and passes the network values into the module call. The module directory holds the interface, resources, outputs, README and example root, and owns both security groups, the counted instances, the target group, attachments, listener and health check. That is the injection pattern from Figure 4.

Every resource address changes.

Without mapping, Terraform plans a replacement. It finds no state entry for the new module address, so it plans to create one; it finds no configuration for the old address, so it plans to destroy it: a new load balancer, a new DNS name, new instances and a short outage. A moved block names the old address in from and the new one in to, so Terraform rewrites the state during the next apply instead of planning a replacement. The plan prints a has-moved-to line per resource and no changes underneath.

Four details decide whether the migration is boring or expensive.

  1. Preserve the arguments that force replacement. The security-group names (p07-alb and p07-web), instance type, subnet assignment, user data and AMI filters must stay identical. A renamed security group forces new groups, which forces new instances because their security-group ids change. Move first, rename second.
  2. Keep the AMI lookup stable. Moving the image data source inside the module changes a data address, which is harmless because data sources are not in state. Changing its filters changes the selected image and replaces the instances.
  3. Do one structural change at a time. Turning the two fixed instances into a counted resource is part of this move, so the blocks map to index 0 and index 1. A later switch to for_each needs its own blocks. One plan should prove one idea.
  4. Keep the blocks until every state has migrated. A block acts only when a plan runs against a state holding the old address, so every environment root and workspace needs one plan and apply before it is safe to delete.

moved works within one configuration. Moving a resource between two roots, and therefore two state files, uses the removed and import pair, or a state-move command.

What the refactor buys is immediate. A second service is a second call with a different service object, and staging is the same module with another backend key and account. None copies the load-balancer wiring.

The lab below is the refactor as a reviewable sequence, with the address mapping as its acceptance criterion.

Lab

Design the web-service contract

Execution status: design-only. Written for Terraform CLI 1.17.1 and AWS provider 6.72.0. No apply is claimed; the cloud steps run in the P07 sandbox after the plan is reviewed.

Prerequisites. Terraform CLI 1.17.1, AWS provider 6.72.0 available to init, a copy of the P07 root, and its sandbox account decision. Keep real account identifiers in the environment.

Acceptance mapping. The lab passes only if these nine addresses line up:

Old addressNew address
aws_security_group.albmodule.web.aws_security_group.alb
aws_security_group.webmodule.web.aws_security_group.web
aws_instance.web_amodule.web.aws_instance.this[0]
aws_instance.web_bmodule.web.aws_instance.this[1]
aws_lb.webmodule.web.aws_lb.this
aws_lb_target_group.webmodule.web.aws_lb_target_group.this
aws_lb_target_group_attachment.amodule.web.aws_lb_target_group_attachment.this[0]
aws_lb_target_group_attachment.bmodule.web.aws_lb_target_group_attachment.this[1]
aws_lb_listener.httpmodule.web.aws_lb_listener.http

The move blocks. One per mapping row; three are shown:

moved {
  from = aws_lb.web
  to   = module.web.aws_lb.this
}

moved {
  from = aws_instance.web_a
  to   = module.web.aws_instance.this[0]
}

moved {
  from = aws_instance.web_b
  to   = module.web.aws_instance.this[1]
}
  1. Write modules/web-service/README.md before moving code: capability, input and output tables, non-goals, destruction notes, owner. If the contract cannot be written from memory, the boundary is not clear.
  2. Add the version file with the CLI floor and the AWS provider range from the widget above. No provider block.
  3. Move the nine resource blocks into the main file. Replace the fixed name prefix with the local name, add the count argument to the instances and attachments, and keep every other argument identical.
  4. Add the four variables and three outputs from the earlier experiment. Re-export endpoint so the P07 check still works.
  5. Replace the root resources with one module "web" call and add the moved blocks above, one per mapping row.
  6. Run init with no backend, then the format check, validate and the provider listing. Expect the constraint to resolve through the root and no provider block inside the module.
  7. In the sandbox root, plan to a saved plan and read it first: expect a has-moved-to line per resource and zero to add, change or destroy. Apply only that plan, then compare the state list with the mapping.
  8. Draw the evidence diagram: root to the web module with the network identifiers on the edge, and no remote-state read anywhere.
  9. Repeat the plan in every other environment state. Delete the moved blocks only after each has applied once, and note the date in the changelog.

Expected observation. No infrastructure change. Every resource keeps its identity, the DNS name is unchanged, and the state list shows the nine addresses under module.web.

Failure checks. Each symptom points at one cause:

  • Replaced security groups mean a name changed.
  • Replaced instances mean the AMI filters, instance type, user data or subnet assignment changed.
  • Destroy-and-recreate for everything means a moved block is missing or its to address is wrong.
  • Root addresses in the state list mean the plan was not applied.

Cost and cleanup. Files and diagrams are free, and a plan is free. The apply runs the P07 billable components, so keep the window short, destroy at the end, and compare the post-destroy inventory with the P07 checklist.

Evidence to keep. The contract README, the example root, the sanitized plan excerpt showing moved addresses with zero changes, and the dependency diagram.

Next in the Series

In Source, Version and Release Terraform Modules, we'll explore Consume modules reproducibly and publish compatible releases through registries or Git.