Skip to content

Lesson 6 of 9 · 26m

Refactoring Terraform Without Destroying the World

Use moved blocks, imports, state migration, and zero-difference plans to restructure code while preserving real infrastructure identity.

The moment a Terraform codebase succeeds, someone wants to reorganize it. Resources move into modules, modules get renamed, states split, and suddenly a cosmetic cleanup proposes destroying the production database. Terraform does not care about your tidy directory structure. It cares about addresses. Refactoring is identity-preserving surgery.

The first rule: plan before and after

Before moving anything, capture a clean plan:

terraform plan -detailed-exitcode

Refactor the code, add migration metadata, then plan again. The desired result is usually no infrastructure changes. If the plan proposes replacement because an address changed, you have not finished the refactor.

Prefer moved blocks over raw state surgery

Modern Terraform supports declarative migration:

resource "aws_security_group" "api" {
  # existing configuration
}

moved {
  from = aws_security_group.web
  to   = aws_security_group.api
}

This records the address migration in code, so every operator and CI runner receives the same instruction. It is much safer than asking each person to run the right terraform state mv in the right order.

Moving into modules changes the whole address

When a resource moves into a module, the address includes module ancestry:

moved {
  from = aws_db_instance.main
  to   = module.database.aws_db_instance.main
}

For nested modules it may become module.platform.module.database.aws_db_instance.main. Count and for_each instances use instance keys: aws_subnet.public["us-east-1a"]. Copy exact addresses from plan output rather than guessing.

Splitting state is a planned extraction

When moving ownership into a new root, the sequence is deliberate:

# old root: make Terraform forget the object without deleting it
terraform state rm aws_iam_role.deploy

# new root: adopt the real object
terraform import aws_iam_role.deploy ci-deploy-role
terraform plan

Between removal and import, nothing owns the object in Terraform. Minimize that window, coordinate operators, and do not run unrelated applies in either root during the migration.

Import is adoption, not code generation

Import brings remote objects under management but does not write matching HCL. You must write the configuration accurately enough that plan differences are intentional:

terraform import aws_s3_bucket.logs acme-access-logs-prod
terraform plan

Some Terraform versions support import blocks and generated configuration. Generated output is a starting point, not production-quality authorship. Remove provider defaults you do not intend to own, or your configuration becomes a copy of someone else's console click history.

Rename infrastructure only when identity allows it

Changing a Terraform label is usually free when moved correctly. Changing the remote resource name often is not. Bucket names, database identifiers, hosted zones, and IAM names may be immutable or globally unique. Distinguish code refactors from remote renames; they have very different risk.

Field notes

  • Move one slice at a time. Big-bang refactors make every plan unreadable and every failure ambiguous.
  • Commit moved blocks with the refactor. Removing them later is optional cleanup after all operators have applied.
  • Verify count and for_each instance keys carefully; migrating the module call does not automatically migrate every child instance correctly.
  • Never state rm a stateful data resource unless the replacement import path is already tested.
  • A successful refactor ends with a boring plan. If the plan is exciting, the refactor is not done.

Was this lesson helpful?

Sign in to rate