Terraform Patterns That Scale: Modules, State, Environments and Policy

How to structure Terraform for growth: module design, remote state, environment layout, drift detection and policy as code, with the trade-offs of each choice.

DIDatainter TeamMAY 06, 20267 MIN READTECHNOLOGY

Terraform makes infrastructure reviewable and repeatable, and a first project of ten resources in a single directory is pleasant. The trouble starts at fifty resources, three environments and four engineers, when state files collide, copy-pasted blocks diverge, and nobody is sure whether production matches the code.

This guide covers the patterns that keep Terraform manageable as it grows: how to design modules, protect and split state, lay out environments, detect drift, and enforce policy automatically. The advice applies equally to OpenTofu, the open-source fork, which keeps the same configuration language and workflow.

Foundations worth getting right early

A few habits pay off immediately:

  • Pin versions. Declare required_version for Terraform and required_providers with version constraints, and commit the .terraform.lock.hcl file. Unpinned providers change behavior between runs and cause confusing diffs.
  • Format and validate in CI. Run terraform fmt -check, terraform validate and a linter such as TFLint on every pull request.
  • Never apply from a laptop in production. Run plan on pull requests and apply from a controlled pipeline with a recorded identity. Laptop applies are how undocumented changes and credentials sprawl begin.
  • Treat plans as the unit of review. Post the plan output to the pull request. Reviewers should read the plan, not just the code diff, because a one-line change can destroy a database.
  • Use prevent_destroy and deletion protection on stateful resources such as databases and storage buckets holding data.

Remote state: protect it like a database

State maps your configuration to real resources and often contains sensitive values in plain text, including database passwords and generated keys. Local state files on a laptop are a liability.

Use a remote backend with locking and encryption: an S3 bucket with a DynamoDB table or native S3 locking (depending on version), Google Cloud Storage, Azure Blob Storage, or a managed service such as HCP Terraform. Enable versioning on the bucket so you can recover from corruption, restrict access with narrow IAM roles, and turn on server-side encryption.

terraform {
  backend "s3" {
    bucket         = "acme-tfstate-prod"
    key            = "network/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "acme-tfstate-lock"
  }
}

Split state by blast radius

One giant state file means every plan takes minutes, every apply locks everyone out, and a mistake can touch the entire estate. Split state along boundaries that match change frequency and ownership:

  • Foundation: accounts, organizations, identity, DNS zones. Changes rarely, high privilege.
  • Network: VPCs, subnets, routing, firewalls. Changes occasionally.
  • Data: databases, queues, storage. Stateful and protected.
  • Services: compute, containers, load balancers, application-specific resources. Changes constantly.

Layers can read each other through terraform_remote_state or, preferably, through data sources that look up resources by tag or name, which avoids tight coupling to another layer’s state format. A rule of thumb: a state file should be small enough to plan in under a couple of minutes and owned by one team.

Technology · Terraform Patterns That Scale: Modules, State, Environments and Policy

Module design

Modules package a reusable unit of infrastructure. Good modules are boring and opinionated; bad ones expose every provider argument as a variable and become a thin, confusing copy of the resource.

Principles:

  • Model a concept, not a resource. A web_service module that creates a load balancer, target group, service and alarms is useful. A security_group_rule module is not.
  • Small, typed interface. Use typed variables with validation, defaults for the common case, and documented descriptions. Output only what consumers need.
  • Compose, do not nest deeply. Keep module trees at two or three levels. Deep nesting makes plans unreadable and dependencies opaque.
  • Avoid provider configuration inside modules. Pass providers in from the root so callers control regions and credentials.
  • Version modules. Publish internal modules in a registry or reference a git tag, never a moving branch. A change to a shared module should be a deliberate upgrade in each consumer.
  • Test them. Terraform’s native terraform test framework and tools such as Terratest verify that a module applies, produces expected outputs and destroys cleanly. Even a single example directory applied in a sandbox account per pull request catches many breakages.
module "api" {
  source  = "git::https://git.example.com/infra/modules.git//web_service?ref=v2.3.0"

  name           = "api"
  environment    = var.environment
  container_image = var.api_image
  cpu            = 512
  memory         = 1024
  desired_count  = var.environment == "prod" ? 3 : 1
}

Prefer the official registry’s well-maintained community modules for commodity pieces (VPCs, for instance) after reading their code, but wrap them in your own module when you want to enforce company defaults.

Environment layout

There are three common ways to separate dev, staging and production, each with trade-offs.

Approach How Pros Cons
Workspaces One configuration, terraform workspace per environment Minimal duplication Easy to apply to the wrong workspace; environments cannot differ structurally; all share one backend config
Directory per environment envs/dev, envs/staging, envs/prod each calling shared modules Explicit, separate state and permissions, safe to diverge Some repetition of module calls
Separate repositories or accounts Environment-specific repos with their own pipelines Strongest isolation and access control More overhead, harder to keep consistent

For most teams, directory-per-environment plus shared versioned modules strikes the best balance. Production lives in its own cloud account or project, with its own state bucket and an approval step. Differences between environments (sizes, replica counts) go in terraform.tfvars files, while the structure comes from the same modules, so staging genuinely resembles production.

Tools such as Terragrunt reduce repetition by generating backend and provider blocks and wiring dependencies between layers. They add another tool to learn, so adopt them when repetition becomes painful, not on day one.

Environments that share modules but not state give you consistency without a shared blast radius.

Secrets and sensitive values

Terraform state may hold secrets even when you mark variables as sensitive, because marking only hides them from output. Do not put secrets in code or .tfvars files in git. Instead:

  • Reference a secrets manager (AWS Secrets Manager, Google Secret Manager, HashiCorp Vault) and let applications fetch values at runtime.
  • Let the provider generate credentials where possible and store only references, such as the managed password feature for some databases.
  • Use ephemeral resources and write-only arguments in recent Terraform versions where providers support them, which keep values out of state.
  • Restrict who can read state to the same people who could read the secrets.

Drift detection and import

Drift happens when reality changes outside Terraform: an engineer edits a security group in the console during an incident, or an autoscaler modifies a resource. Left alone, the next apply may revert the emergency fix or fail unexpectedly.

Counter it with:

  • Scheduled plans. Run terraform plan -detailed-exitcode nightly in CI for each state. Exit code 2 means differences exist; send a notification with the plan summary. Many teams create a ticket automatically.
  • Restricted console access. Make production read-only for humans, with a break-glass role for incidents that is audited and followed by a code fix.
  • A reconciliation habit. After an emergency console change, codify it the same day, or revert it.
  • Import blocks. Bring existing resources under management declaratively with import blocks and terraform plan -generate-config-out to draft the configuration, then clean it up. Adopt legacy infrastructure gradually, layer by layer, rather than in one heroic migration.
  • Ignore changes sparingly. lifecycle { ignore_changes = [...] } is appropriate for attributes managed elsewhere (autoscaling desired counts), but each use is a small hole in your guarantees.

Policy as code

Review by humans does not scale and misses repetitive mistakes. Encode your rules and run them in the pipeline between plan and apply.

  • Static analysis of configuration: tools like Checkov, Trivy (config scanning) and tfsec detect public buckets, unencrypted disks and open security groups before anything is deployed.
  • Plan-based policy: Open Policy Agent (with Conftest) or HashiCorp Sentinel evaluate the JSON plan (terraform show -json plan.out) against rules such as “all resources must have an owner tag,” “no instances larger than a set size in dev,” “databases must have deletion protection,” or “no changes to IAM outside the security team’s pipeline.”
  • Cost estimation: Infracost comments on the pull request with the monthly cost change, which prompts useful questions at review time.
  • Cloud-native guardrails: service control policies and organization policies prevent actions regardless of what Terraform says, acting as a last line of defense.

Start with a small set of high-value rules, run them in warning mode, tune out false positives, and promote them to blocking. A policy suite that blocks everything on day one gets bypassed.

A pipeline sketch

  1. Pull request opens: fmt, validate, lint, security scan, then plan for affected directories only (detect changes by path).
  2. Policy checks and cost estimate run against the plan; results post as comments.
  3. Reviewer approves after reading the plan. The plan file is stored as an artifact.
  4. On merge, a pipeline applies the saved plan (or re-plans and compares) using short-lived OIDC credentials, one state at a time, with environment approvals for production.
  5. Nightly drift detection posts alerts for any state with changes.

In our work at Datainter, the largest recurring cost has been unclear ownership of state files, so we list the owning team and escalation contact in a short README next to every root module.

Key takeaways

  • Pin provider and Terraform versions, validate in CI, and apply only from a pipeline; make the plan the unit of code review.
  • Keep remote state encrypted, versioned and locked, and split it by blast radius and change frequency: foundation, network, data, services.
  • Design modules around concepts with small typed interfaces, shallow nesting and versioned releases, and test them.
  • Prefer directory-per-environment with shared versioned modules, with production isolated in its own account and state.
  • Detect drift with scheduled plans, restrict console access, and bring legacy resources in with import blocks.
  • Enforce policy as code (static scanning, plan-based rules, cost estimates) starting in warning mode before blocking.
#terraform#infrastructure as code#devops#cloud
DI
Datainter TeamEngineers, designers and operators building software and fintech products from Medellín, Tigard and Luxembourg.

Building something in this space?

Talk to the team that ships and operates it. We reply within one business day.

Start a project
Chat with us on WhatsAppUSUALLY REPLIES WITHIN MINUTES