Subscribe

Refactoring Terraform safely with moved, import and removed blocks

Rename resources, move them into a module, adopt hand-built ones and stop managing others, all without Terraform destroying anything. Runnable demo with moved, removed and import blocks on Terraform 1.17.

Refactoring Terraform safely with moved, import and removed blocks

Terraform code collects bad names over time. A bucket called b. A security group that should have been in a module from day one. An IAM user that another team now wants to own. The code is easy to change. The state is the scary part, because Terraform tracks every object by its address, and if the address changes Terraform thinks you deleted one thing and asked for a new one.

In this blog we will look at the three blocks that fix this without touching the real resources: moved, removed and import. This is an intermediate post. You should know plan and apply (see your first EC2 instance with plan and apply) and what a module is (see writing a reusable Terraform module). I used Terraform 1.17.1 and AWS provider 6.73.0.

Why a rename is dangerous

Let us start with the problem, so the fix makes sense. I wanted to show it without an AWS account, so I wrote a tiny config with the local provider. It has a file called local_file.f. I applied it, renamed the resource to local_file.notes and ran plan again.

  # local_file.f will be destroyed
  # (because local_file.f is not in configuration)
  # local_file.notes will be created
Plan: 1 to add, 0 to change, 1 to destroy.

For a text file, who cares. For an S3 bucket with your backups or an RDS instance, that plan is a disaster waiting for someone to type yes. Before Terraform 1.1 the answer was terraform state mv, run by hand, against the live state, with no review. I never liked that. Basically nobody sees it in the pull request.

Renaming with moved

A moved block tells Terraform that the object at the old address is now at the new one. It goes in any .tf file in the same module.

resource "aws_s3_bucket" "backups" {
  bucket = "example-com-backups"
}

moved {
  from = aws_s3_bucket.b
  to   = aws_s3_bucket.backups
}

Here is what the plan said in my local demo after I added the moved block for the same rename.

  # local_file.f has moved to local_file.notes
    resource "local_file" "notes" {
        id                   = "86cad8b1a78128ea752c39eb69ba74fb0dfc2c06"
        # (10 unchanged attributes hidden)
    }
Plan: 0 to add, 0 to change, 0 to destroy.

Zero of everything. That's the line to look for. If the plan shows any change next to a move, it means you changed something else in the same commit, and I'd split that into two pull requests so the move is boring on its own.

The same block handles count to for_each, which is the other refactor everyone does sooner or later.

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

Moving into a module

This is where moved really pays off. Say the web security group and its ingress rule lived in the root module and you now want them in modules/web_sg. Inside the module the resource is called this.

module "web_sg" {
  source = "./modules/web_sg"
  vpc_id = var.vpc_id
}

moved {
  from = aws_security_group.web
  to   = module.web_sg.aws_security_group.this
}

moved {
  from = aws_vpc_security_group_ingress_rule.https
  to   = module.web_sg.aws_vpc_security_group_ingress_rule.https
}

You need one moved block per resource. A module can't be moved in one line unless the whole module moves (for example module.a to module.b, that works). Forget the rule's block and the plan will delete and recreate the rule, which on a security group means a few seconds with no HTTPS. Read the plan every time.

In the local demo the module move came out like this.

  # local_file.cfg has moved to module.site.local_file.cfg
Plan: 0 to add, 0 to change, 0 to destroy.

How long do you keep these blocks? The docs say keep them as long as anyone might still have a state with the old address. For a single root module with one state in S3 (like the one in storing Terraform state in S3 with native locking), once the apply has gone through, the old address is gone everywhere and the block can go. For a module other people use, keep them for a long time, since you don't know when they'll upgrade.

Stopping management with removed

Sometimes you want Terraform to forget a resource but leave it alone in AWS. Another team takes over the CI user, or you're splitting a big state into two. The old way was terraform state rm, again by hand. Since Terraform 1.7 there is a removed block.

removed {
  from = aws_iam_user.ci

  lifecycle {
    destroy = false
  }
}

Delete the resource "aws_iam_user" "ci" block in same change. The destroy = false part is the whole point. Leave it out and the default is destroy = true, which means Terraform destroys it, same as just deleting the resource block. I find that default a bit odd honestly, but it's how it works.

My demo plan said it very clearly.

 # local_file.notes will no longer be managed by Terraform, but will not be destroyed
 # (destroy = false is set in the configuration)
Plan: 0 to add, 0 to change, 0 to destroy.
Warning: Some objects will no longer be managed by Terraform

After the apply, terraform state list no longer showed local_file.notes, and ls out/ still showed notes.txt. That's exactly what you want for the IAM user.

Adopting with import

The third one is the reverse: something exists in AWS and Terraform should start managing it. I wrote a whole post on this when I moved the AWS account behind this blog into code, importing hand-built AWS resources into Terraform. That one covers the key pair that wanted to be replaced and prevent_destroy, so I won't repeat it here.

Two newer things are actually worth knowing. Since 1.7 an import block can take for_each. And since 1.12 you can give an identity instead of a raw id string, for resources whose provider supports it. AWS provider 6.x has identity schemas for a lot of resources (582 in the version I ran, I counted from terraform providers schema -json).

resource "aws_cloudwatch_log_group" "app" {
  for_each          = toset(["shorty", "worker"])
  name              = "/app/${each.key}"
  retention_in_days = 30
}

import {
  for_each = toset(["shorty", "worker"])
  to       = aws_cloudwatch_log_group.app[each.key]
  identity = {
    name = "/app/${each.key}"
  }
}

To find out which keys a resource takes, look at the import section on its registry page, or dump the schema and look under resource_identity_schemas.

terraform providers schema -json \
  | jq '.provider_schemas["registry.terraform.io/hashicorp/aws"].resource_identity_schemas.aws_cloudwatch_log_group'

The plan should say "to import" and nothing else. In my local demo I imported a random_integer (the local provider doesn't support import, I found that out only when the plan errored with "Resource Import Not Implemented").

Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.

Try it without an AWS account

All of the above ran for real on my Mac, in one working directory with one state file, stage by stage. The script copies each stage's .tf files in, then runs fmt, validate, plan to a file and apply of that file.

#!/bin/bash
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
WORK="$HERE/work"
rm -rf "$WORK"
mkdir -p "$WORK"
for stage in 1 2 3 4 5; do
  echo "===== stage $stage ====="
  find "$WORK" -maxdepth 1 -name '*.tf' -delete
  rm -rf "$WORK/modules"
  cp -r "$HERE/stages/$stage/." "$WORK/"
  terraform -chdir="$WORK" init -input=false -no-color >/dev/null
  terraform -chdir="$WORK" fmt -check -recursive
  terraform -chdir="$WORK" validate -no-color
  terraform -chdir="$WORK" plan -input=false -no-color -out=stage.tfplan
  terraform -chdir="$WORK" apply -input=false -no-color stage.tfplan
  terraform -chdir="$WORK" state list
done

Stage 1 creates two files. Stage 2 renames one, stage 3 moves the other into ./modules/site, stage 4 removes the first with destroy = false and stage 5 imports a number. The final state list was just this.

random_integer.port
module.site.local_file.cfg

Doing it with throwaway providers first is a habit I'd recommend before any big refactor. You see the plan output shapes once, on something that can't hurt, and then the real plan on AWS has no surprises.

A checklist I follow

  • One kind of change per pull request. Moves in one, real changes in the next.
  • Plan to a file, read it, apply that file.
  • "0 to destroy" on every refactor plan, no exceptions. If it isn't zero, stop.
  • Check terraform state list before and after.
  • Take a copy of the state first (terraform state pull > before.tfstate). With S3 versioning on you have one anyway, but a local copy is quicker to diff.

That's it. Next time a name bothers you, fix it with a moved block and an empty plan.