how/state
Three commands that edit the state file directly: rename an entry, forget a resource, pull an existing one in from the cloud. What they change, what they leave alone, and where they bite.
terraform.tfstate is Terraform's cache, and usually you don't have to
touch it by hand. Apply writes everything in for you, refresh updates everything for you.
But there are cases where state and HCL diverge by address rather than by value:
For each case there is a command: state mv, state rm, import.
All three are imperative: they change state in place, the HCL stays on you.
Hit ▶ and watch what each one does to the HCL/state/cloud triangle.
One S3 bucket is described in HCL as aws_s3_bucket.old, state has
an entry with id linuxlab-3f4a, and in AWS there is a bucket with exactly that
id. All three sources agree.
From this point we split three ways: rename, remove, import.
recap
What matters about these three operations:
When you can and should use them:
state mv: rename a resource or move it into another module
without recreating it. The most common case.state rm: hand a resource over to another team or an outside system.
The bucket keeps living, Terraform just stops tracking it.
Often paired with terraform import on the new owner's side.terraform import: bring a long-existing resource under management.
The alternative is to recreate it from scratch, which for prod data
is rarely possible.Gotchas:
state rm does not warn about dependencies. If you removed a resource from
state that others depend on, after plan they all start crying "this needs to be
created again."terraform import brings only the id into state. The attributes
(tags, policies, encryption) you have to write into HCL by hand,
then plan should show No changes. If it shows anything else, the
state does not match what you described.Terraform 1.5+ added declarative equivalents: the moved,
removed, and import blocks. They are reproducible and live in git. That is
the topic of the next explainer: tf-moved-removed-import-blocks.