Lesson 7 of 8 · 11 min · Structure and safety
Importing, refactoring safely and lifecycle rules
What you will learn
- Adopting infrastructure that was created by hand
- Renaming and restructuring without destroying resources (
moved) lifecycle:prevent_destroy,create_before_destroy,ignore_changes,replace_triggered_by- Forcing replacement (
-replace), the danger of-target, and previewing destruction
In simple words
Real projects are untidy. Some things were made by hand before Terraform arrived, and code gets renamed and reorganised. Done carelessly, Terraform may think a renamed server is a new one and destroy the old. This lesson shows how to bring existing things in and reorganise safely.
Words to know
- Import: bringing something that already exists under Terraform's management.
- moved block: telling Terraform that a resource was renamed, not replaced.
- Lifecycle: settings that change how Terraform creates, updates or destroys one resource.
- prevent_destroy: a lifecycle setting that refuses to delete an important resource.
Importing existing resources
Most real environments have resources created by hand before Terraform arrived. Importing attaches an existing object to a resource block, so Terraform manages it from now on without recreating it.
The modern, reviewable way is an import block (Terraform 1.5+). We created a bucket outside Terraform, then wrote:
resource "aws_s3_bucket" "legacy" {
bucket = "legacy-bucket-made-by-hand"
}
import {
to = aws_s3_bucket.legacy
id = "legacy-bucket-made-by-hand"
}
terraform plan showed:
# aws_s3_bucket.legacy will be imported
Plan: 1 to import, 1 to add, 0 to change, 0 to destroy.
and apply performed it: aws_s3_bucket.legacy: Import complete [id=legacy-bucket-made-by-hand]. The id format depends on the resource type: the Import section at the bottom of each resource's page in the provider documentation tells you (a bucket name, an instance id, vpc-123, cluster/service pairs...). After the import is applied you can remove the import block.
Procedure that keeps you safe:
- Write the resource block with the arguments you believe match reality.
- Add the
importblock and runterraform plan. The plan shows what would change on the imported object: if it shows updates (~), your configuration differs from reality. Edit the code until the plan is empty (or the changes are ones you want). - Apply, then commit.
terraform plan -generate-config-out=generated.tf can write a first draft of the resource block for you from the real object; review and clean it up (it includes many default arguments). For large estates, tools such as terraformer or cloud-provider exporters (Azure aztfexport) help, but always review.
The older command form terraform import aws_s3_bucket.legacy legacy-bucket-made-by-hand still works, but changes state immediately without a reviewable plan.
Importing does not "fix" the real object; it only records it. A mismatch will show in the next plan.
Refactoring with `moved`
Resource addresses are identities. If you rename a resource, move it into a module or change count to for_each, Terraform sees "old address gone, new address added" and plans a destroy plus a create, which for a database is a disaster. A moved block tells Terraform "this is the same object":
resource "local_file" "nodes" { # was: local_file.count_demo
count = 2
filename = "${path.module}/out/node-${count.index}.txt"
content = "node ${count.index}\n"
}
moved {
from = local_file.count_demo
to = local_file.nodes
}
The plan after renaming:
# local_file.count_demo[0] has moved to local_file.nodes[0]
# local_file.count_demo[1] has moved to local_file.nodes[1]
Plan: 0 to add, 0 to change, 0 to destroy.
No infrastructure changes; only the state addresses are rewritten. moved blocks are code, so they are reviewed in pull requests and applied automatically for everyone who runs the configuration (unlike a manual terraform state mv that only affects one state). Typical uses:
- rename a resource:
from = aws_instance.web,to = aws_instance.app; - move a resource into a module:
from = aws_s3_bucket.logs,to = module.storage.aws_s3_bucket.logs; - change
counttofor_each:from = aws_subnet.public[0],to = aws_subnet.public["a"]; - module authors add
movedblocks inside the module when they rename internals, so users' states migrate on upgrade.
Keep the moved blocks for a while (or permanently in shared modules) so that everyone who has not yet applied still migrates. There is also a removed block (removed { from = aws_x.y; lifecycle { destroy = false } }) to stop managing a resource without destroying it, the declarative form of state rm.
lifecycle rules
The lifecycle block inside a resource tunes how Terraform treats it:
resource "aws_s3_bucket" "important" {
bucket = var.bucket_name
lifecycle {
prevent_destroy = true
}
}
| Setting | Effect |
|---|---|
prevent_destroy = true |
any plan that would destroy this resource (including replacement or destroy) fails with an error. Use on databases, state buckets, encryption keys |
create_before_destroy = true |
when replacing, create the new one first, then delete the old (for zero downtime). Needs unique-name tolerance (names with name_prefix) |
ignore_changes = [attr, ...] |
do not treat differences in those attributes as changes: for values something else manages (autoscaler desired size, tags added by another tool) |
replace_triggered_by = [other.resource] |
replace this resource whenever another changes |
precondition / postcondition |
custom checks with clear error messages before or after the resource is created |
What prevent_destroy does when someone runs terraform destroy:
Error: Instance cannot be destroyed
Resource aws_s3_bucket.important has lifecycle.prevent_destroy set, but the
plan calls for this resource to be destroyed.
It protects against accidents in the code, but removing the resource block (or the flag) removes the protection, so also use the platform's own guard rails: deletion protection on databases, S3 versioning and MFA delete, resource policies, and restrictive IAM so the pipeline cannot delete production data stores without extra approval.
Forcing replacement and previewing destruction
terraform plan -replace=aws_instance.web # recreate this one resource (replaces the old "taint")
terraform plan -destroy # what would terraform destroy remove?
Our run printed # aws_s3_bucket.important will be replaced, as requested with Plan: 1 to add, 0 to change, 2 to destroy (including an unmanaged-by-config bucket in state), and plan -destroy listed every resource that would be removed. Use -replace to rebuild a broken or corrupted instance.
`-target`: a sharp tool
terraform apply -target=aws_s3_bucket.important limits the operation to one resource and its dependencies. Terraform warns every time:
Warning: Resource targeting is in effect
Targeting skips the rest of the graph, so state and reality can drift apart (resources that depend on changed attributes are left stale), and a later full plan may show surprising changes. Acceptable for recovering from an incident or breaking a dependency deadlock; not a normal workflow. If you need to apply parts independently, split them into separate states instead.
Handling a failed apply
Terraform does not roll back. If an apply fails halfway, resources created so far remain in the state and the rest are not created: fix the cause (permissions, quota, name collision) and run apply again; Terraform picks up where it left off. If a resource was created in the cloud but the apply died before recording it (a crash), the next plan will try to create it again and fail on a name conflict: import it. Keep apply runs small and frequent, to limit the damage of any one failure.
Common mistakes
- Importing without matching the configuration, then applying a plan that modifies the real object.
- Renaming resources without
moved, destroying production resources. - Relying on
prevent_destroyas the only protection. ignore_changeson important attributes, hiding real drift forever.- Using
-targetregularly. - Using
terraform taint(deprecated) instead of-replace. - Hand-editing state instead of
moved/import/removedblocks.
Try it yourself
- Create a bucket (or any resource) by hand, write a resource block and
importblock, and make the plan empty. - Rename a resource and add a
movedblock; confirm the plan shows no create or destroy. - Add
prevent_destroyto a resource and tryterraform destroy. Then tryplan -destroyon the whole stack. - Replace one resource with
-replace, and read what else the plan wants to change.
Check yourself
What does an import block do?
It binds an existing real object to a resource address in the state, so Terraform manages it without creating a new one. The plan shows what would change so you can align the code first.
Why use a moved block instead of just renaming a resource?
Without it Terraform interprets a rename as destroying the old resource and creating a new one. moved tells it to keep the existing object and only change its address.
What does prevent_destroy do and what does it not do?
It makes any plan that destroys the resource fail. It does not protect against removing the flag or resource block, or against deletion outside Terraform.
Why avoid -target in regular workflows?
It skips the dependency graph's other parts, which can leave state and infrastructure inconsistent and hide changes that a full plan would surface.
Interview questions
Your team created infrastructure manually for two years. How do you move it into Terraform?
Inventory it, then adopt incrementally: write resource blocks and import blocks per component (starting with stable foundations), iterate until plans are empty, commit, split into states by layer, add CI plans, and restrict console changes afterwards.
You need to rename a module and restructure code without downtime. How?
Add moved blocks mapping every old address to the new one, run plan and verify there are zero creates/destroys, merge, and apply.
A resource creation failed halfway through an apply. What now?
Fix the cause and re-run apply; Terraform resumes from the recorded state. If an object exists in the cloud but not in state, import it. Never rerun with -target hoping to skip the problem.
Summary
importblocks adopt existing resources reviewably; make the plan empty before applying.movedblocks refactor addresses without destroying anything;removedstops managing without deleting.lifecycle(prevent_destroy,create_before_destroy,ignore_changes) protects and tunes resources; combine with platform deletion protection.- Use
-replaceto rebuild,plan -destroyto preview, and avoid-target; rerun a failed apply rather than editing state.
Going deeper
- Import: import blocks: bulk and config-generated imports.
- Refactoring with moved blocks: renaming, moving and splitting.
- The lifecycle meta-argument: all lifecycle settings.
- Resource targeting: why and when.
See how much of this you can explain
A free mock interview asks you new questions on Infrastructure as Code with Terraform for DevOps Engineer and scores every answer, with what to fix.