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 Joshua Sequeira, founding engineer running Terraform in production. Updated .
By the end you can
0 of 5
Live lab in this chapter
A real-feeling terminal and a live cluster map, right in your browser. Every command block below has a ▶ Run in lab button.
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?
main.tf
terraform plan
The rule that follows:
- Things with names (buckets, users, DNS records, services):
for_eachover a set or a map. - Interchangeable copies (three identical workers):
countis fine. - Optional resources:
count = var.enabled ? 1 : 0is 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:
# 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 {
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.
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:
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:
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:
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]
}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:
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.
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
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