Short answer: Split Terraform into reusable modules, each one building block with safe defaults, and small stacks that combine them for one part of one environment, each with its own locked state in S3. Pin stacks to module versions, refactor with moved blocks, bring existing resources in with import blocks, and apply only from the pipeline.
How Terraform goes wrong as a platform grows
Most Terraform starts as one directory that builds everything. That works for the first few services. Then every new service is copied from the last one with small changes, the plan for a one-line change takes minutes and touches hundreds of resources, and nobody wants to run apply.
Anwar has designed a reusable Terraform module structure used to rebuild a platform on one consistent pattern. This is the approach in outline.
Two layers: modules and stacks
- Modules describe one building block: a network, a service, a database, a queue. They take inputs, create resources and return outputs. They don’t know which environment they’re in.
- Stacks (root modules) combine modules for one part of one environment, such as “production networking” or “staging, orders service”. Each stack has its own state.
Every environment uses the same modules with different inputs. Staging becomes a smaller copy of production rather than a close guess.
A layout that works for most growing platforms:
terraform-modules/ # its own repository, released with version tags network/ ecs-service/ aurora-mysql/ queue/ platform/ # the stacks prod/ network/ main.tf backend.tf cluster/ main.tf backend.tf orders/ main.tf backend.tf staging/ network/ main.tf backend.tf cluster/ main.tf backend.tf orders/ main.tf backend.tf
What makes a good module
- One job. A “service” module that creates the container service, its load balancer rule, log group, alarms and IAM role is easier to reuse than one that also creates the network.
- Few, meaningful inputs with safe defaults. Encryption on, logs retained, deletion protection on in production. A new service should need a handful of values, not fifty.
- The standard layout.
main.tf,variables.tf,outputs.tfand a README, so anyone can read any module. - No provider configuration inside. Child modules inherit providers from the stack that calls them.
for_eachovercountfor collections, so adding or removing one item doesn’t renumber and recreate the others.- Inputs that check themselves.
validationblocks reject bad values at plan time, with a message that says what to fix.
variable "name" { type = string description = "Service name, used in resource names and tags" } variable "cpu" { type = number default = 256 description = "Fargate CPU units" validation { condition = contains([256, 512, 1024, 2048, 4096], var.cpu) error_message = "cpu must be one of 256, 512, 1024, 2048 or 4096." } } variable "deletion_protection" { type = bool default = true # safe by default; staging can turn it off }
Version modules, and upgrade one stack at a time
Publish modules with version tags, from a registry or a Git tag, and pin each stack to a version. A change to a module then reaches staging first, and production only when someone moves its pin. Without versions, changing a module changes every environment at the next apply.
module "orders" { source = "git::https://github.com/your-org/terraform-modules.git//ecs-service?ref=v1.4.0" name = "orders" cpu = 512 }
Use semantic versions: a patch or minor release must not change existing resources, and anything that would is a major release with upgrade notes.
Refactoring without recreating resources
Moving existing resources into modules changes their addresses, and Terraform would otherwise destroy and recreate them. A moved block tells Terraform it’s the same resource:
moved {
from = aws_s3_bucket.logs
to = module.logging.aws_s3_bucket.this
}For infrastructure that was built in the console, an import block brings it under Terraform in a normal plan and apply, so the change can be reviewed like any other. Terraform can draft the configuration for you:
terraform plan -generate-config-out=generated.tf
The generated code is a starting point, not the finished module: it hard-codes every attribute. Move what matters into module inputs, delete the rest, and keep going until the plan shows no changes.
State: small, separate and locked
Keep state remote, in S3 with locking, with one state file per stack. Smaller states mean faster plans, and a mistake in one stack can’t reach another. Read another stack’s outputs through data sources or remote state, rather than sharing one big state.
terraform { backend "s3" { bucket = "acme-terraform-state" key = "prod/orders.tfstate" region = "ap-southeast-2" encrypt = true use_lockfile = true # S3-native locking; DynamoDB locking is deprecated } }
Turn on versioning for the state bucket, so a bad apply can be undone by restoring the previous state file.
Run it in the pipeline
Plan on every pull request and post the plan for review. Apply only from the pipeline after merge. Schedule a plan to flag anything changed by hand. See Terraform and infrastructure as code and Faster deployments.
Common mistakes
- Modules that wrap one resource. A module around a single bucket adds indirection without adding a decision. Modules earn their place by combining resources with the right defaults.
- Environment logic inside modules.
if env == "prod"in a module couples it to your environments. Pass the behaviour in as an input instead. - Unpinned providers. A new major provider version arriving at the next
initcan change plans everywhere at once. Pin versions and commit the lock file. - Refactoring without
movedblocks. The plan shows a destroy and a create. Read every plan that contains a destroy before applying it.
Sources
- HashiCorp: Standard module structure
- HashiCorp: Refactoring modules (moved blocks)
- HashiCorp: Import blocks
- HashiCorp: S3 backend
See also Terraform consulting.
Keep reading
Related articles
Next step
Want a review of your Terraform?
On a 30-minute call we’ll look at how your code is structured and where to start improving it.