CD4: Terraform for teams

Lesson 5 of 5 · reading 15–25 minutes; practice and project time is on the module page

Refactoring, importing and OpenTofu

🎯You'll be able to

Rename or move resources without recreating them, bring existing infrastructure under Terraform, and explain how OpenTofu relates to Terraform.

🏠The everyday picture

When a city renames a road, the houses don't move; only the address changes, and the post office updates its records. And when a new municipality takes over an old village, it adds the existing houses to its register instead of rebuilding them.

📘What it really is

📝A worked example

Input: in your finished kit, rename docker_container.lb to docker_container.load_balancer (and anything that refers to it), add the moved block above, and run terraform plan.

Expected output: docker_container.lb has moved to docker_container.load_balancer and Plan: 0 to add, 0 to change, 0 to destroy. Remove the moved block and plan again: Terraform now proposes to destroy docker_container.lb and create docker_container.load_balancer, which would interrupt traffic. Put the block back.

🌍Where it's used

📝Case scenario

A media company decided to manage its hand-built DNS records with Terraform. A first attempt wrote new records with the same names and applied them, which failed with conflicts and briefly broke email. The second attempt used import blocks: the plan showed 120 records will be imported and zero changes, which was approved, and from then on DNS changes went through pull requests.

🖱️Try it

Create a volume by hand: docker volume create routerani-dev-uploads. Add a docker_volume.uploads resource with that name and the import block above, and run terraform plan, then terraform apply. Success: the plan shows 1 to import, 0 to add, and afterwards terraform state list includes docker_volume.uploads. Remove the resource with a removed block if you don't want to keep it.

⚠️Common mistakes

🛠️For your project

If you rename anything in RouteRani's Terraform during the projects, add moved blocks so the plan shows no replacements.

✅Quick check

What does a moved block do?

Show the answer

Tells Terraform a resource has a new address, so it updates state instead of destroying and recreating it.

What is OpenTofu?

Show the answer

An open-source fork of Terraform, with the same language and providers and the tofu command.

← PreviousReviewing infrastructure changes
ProLearners Assist