Skip to Content

Terraform Field Guide · Chapter 8 of 12

Lifecycle, imports and refactoring

Code changes. Resources get renamed, lists grow, someone built a bucket by hand three years ago, and the production database must never be deleted by a typo. Learn the tools for changing Terraform code without touching what is running: for_each, moved, import, removed and lifecycle rules.

  • 45 min
  • Intermediate
  • Hands-on
  • Free

By , founding engineer running Terraform in production. Updated .

count: remove "uploads"for_each: remove "uploads"[0] logsunchanged[1] uploadsreplaced by backups[2] backupsreplaced by reports[3] reportsdestroyed["logs"]unchanged["uploads"]destroyed["backups"]unchanged["reports"]unchangedmovedimportremovedprevent_destroychange the code without touching what is running
The chapter in one pictureKey resources by name, not position, and use moved, import and removed blocks to change code without touching what is running.

By the end you can

0 of 5

count or for_each

Both create several copies of a resource from one block. The difference is how each copy is identified. count numbers them: b[0], b[1], b[2]. for_each names them: b["logs"], b["uploads"]. That sounds cosmetic until the list changes:

Interactive · count or for_each

Remove one bucket from the list. What does the plan do to the others?

Click a name to remove it, or

main.tf

terraform plan

The rule that follows:

  • Things with names (buckets, users, DNS records, services): for_each over a set or a map.
  • Interchangeable copies (three identical workers): count is fine.
  • Optional resources: count = var.enabled ? 1 : 0 is the common idiom.

Renames with moved

Renaming a resource, moving it into a module or switching from count to for_each all change its address. To Terraform, a new address with no history looks like a new resource, and the old address with no code looks like one to destroy. A moved block connects the two:

buckets.tf
# Before: resource "aws_s3_bucket" "b" { count = 4 ... }
resource "aws_s3_bucket" "b" {
  for_each = toset(var.buckets)
  bucket   = "acme-${each.key}"
}

moved {
  from = aws_s3_bucket.b[0]
  to   = aws_s3_bucket.b["logs"]
}

moved {
  from = aws_s3_bucket.b[1]
  to   = aws_s3_bucket.b["uploads"]
}
Says "the object at from is now at to". Terraform updates state during the next apply, without touching the bucket.
The old address, from the count version.
The new address. One moved block per object.

The plan shows # aws_s3_bucket.b[0] has moved to aws_s3_bucket.b["logs"] and 0 to destroy. Unlike terraform state mv from chapter 3, the move is in the code: reviewed in a pull request, and applied to every environment that uses it. Leave moved blocks in place for a while so every environment and every module caller catches up.

Adopting with import

Almost every team has resources that were built by hand before Terraform arrived. An import block brings one under management without recreating it:

import.tf
import {
  to = aws_s3_bucket.reports
  id = "acme-legacy-reports"
}

resource "aws_s3_bucket" "reports" {
  bucket = "acme-legacy-reports"
}
The address it will have in your code.
How the provider finds the real object. Each resource's Registry page has an "Import" section saying what the ID is: a name, an ARN, a composite string.
The matching block. Its arguments must describe the bucket as it is, or the plan will show changes.
Let Terraform draft the block
terraform plan -generate-config-out=generated.tf
  # aws_s3_bucket.reports will be imported
  # (config will be generated)
    resource "aws_s3_bucket" "reports" {
        bucket = "acme-legacy-reports"
        ...
    }

Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.
-generate-config-out
With an import block and no resource block, Terraform writes a starting resource block into generated.tf. Tidy it up: it includes every attribute, defaults and all.
1 to import
Apply records the bucket in state. Nothing changes in AWS.

Import one resource at a time, plan until it says No changes apart from the import, then apply. Older guides use the terraform import command; the block does the same through a normal plan, and can import many resources in one reviewed change.

Letting go with removed

The opposite case: you want Terraform to stop managing something, without deleting it. Perhaps another team is taking it over. Deleting the block would plan a destroy. A removed block makes the intent explicit:

handover.tf
removed {
  from = aws_s3_bucket.reports

  lifecycle {
    destroy = false
  }
}
Forget it from state, leave it running. The code-reviewed version of terraform state rm.

Lifecycle rules

Every resource accepts a lifecycle block that changes how Terraform treats it. Three you will actually use:

main.tf
resource "aws_db_instance" "main" {
  identifier = "shop-prod"
  # engine, size, storage, credentials

  lifecycle {
    prevent_destroy = true
  }
}

resource "aws_launch_template" "web" {
  name_prefix = "web-"
  # image, instance type, user data

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_ecs_service" "shop" {
  name          = "shop"
  desired_count = 2

  lifecycle {
    # The autoscaler changes this all day. Do not fight it.
    ignore_changes = [desired_count]
  }
}
Any plan that would destroy this resource fails with an error. Put it on databases and state buckets.
When a replacement is needed, build the new one first. The plan shows +/- instead of -/+. Needs a name that can exist twice, hence name_prefix.
Stop proposing to reset an attribute something else manages, like an autoscaler. Use sparingly: ignored drift is invisible drift.

Hands-on: refactor without a destroy

Start with a count-based configuration and apply it:

main.tf
terraform {
  required_providers {
    local = { source = "hashicorp/local", version = "~> 2.5" }
  }
}

variable "names" {
  default = ["logs", "uploads", "backups"]
}

resource "local_file" "f" {
  count    = length(var.names)
  filename = "${path.module}/out/${var.names[count.index]}.txt"
  content  = var.names[count.index]
}
Apply the count version
terraform init
terraform apply -auto-approve
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.

Now switch to for_each. Replace the resource block with this, and add the moved blocks:

main.tf
resource "local_file" "f" {
  for_each = toset(var.names)
  filename = "${path.module}/out/${each.key}.txt"
  content  = each.key
}

moved {
  from = local_file.f[0]
  to   = local_file.f["logs"]
}

moved {
  from = local_file.f[1]
  to   = local_file.f["uploads"]
}

moved {
  from = local_file.f[2]
  to   = local_file.f["backups"]
}
Without these three blocks, the plan destroys three files and creates three. Try removing them first to see it.
Plan the refactor
terraform plan
  # local_file.f[2] has moved to local_file.f["backups"]
    resource "local_file" "f" {
        id                   = "829e977414c1..."
        # (10 unchanged attributes hidden)
    }

  # local_file.f[0] has moved to local_file.f["logs"]
  # local_file.f[1] has moved to local_file.f["uploads"]

Plan: 0 to add, 0 to change, 0 to destroy.
has moved to
State will be updated on apply. The files are not touched.
0 to destroy
The goal of every refactor.

Apply it, then remove "uploads" from the list and plan: one file to destroy, the others untouched.

Mini mission

Protect a file from deletion

Add prevent_destroy = true to the files, then remove "backups" from the list and plan. Read the error. How would you delete it on purpose?

Reveal one safe solution
Terminal
terraform plan
│ Error: Instance cannot be destroyed
│
│ Resource local_file.f["backups"] has lifecycle.prevent_destroy set, but the
│ plan calls for this resource to be destroyed. To avoid this error and
│ continue with the plan, either disable lifecycle.prevent_destroy or reduce
│ the scope of the plan using the -target option.

To delete it on purpose, remove prevent_destroy in the same pull request that removes the item, so a reviewer sees both changes together. That is the point of the guard: a destroy has to be a deliberate, visible decision, never a side effect.

Check yourself

Quiz

0 of 5 answered

  1. 1. Four buckets are created with count from a list. You remove the second name. What does the plan do?
  2. 2. When is count still the right choice?
  3. 3. What does a moved block do?
  4. 4. Someone created a bucket in the console years ago. How do you bring it under Terraform?
  5. 5. What does prevent_destroy = true do?

Further reading