How to properly reset Terraform default tfstate?
Asked Answered
R

1

6

Recently, I've started using workspace per env in my Terraform configuration. I ended up having three workspaces dev, staging and production. But for historical reasons my default workspace still contains obsolete tfstate.

What is the proper what to "reset" it to the default state? Like having nothing in it.

One way to achieve this is to manually execute terraform state rm for each resource. But in this way, I would end up with hundreds of such calls. Is there some kind of terraform state reset analogue?

Rob answered 5/11, 2021 at 23:29 Comment(7)
What do you mean by a "default state"?Handclasp
@Handclasp simply saying to detach all resources from tfstate without corrupting default.tfstate file.Rob
Sorry, but its not clear what you mean. TF state file is called terraform.tfstate. Not sure what is default.tfstate?Handclasp
You can just delete the entire state file and re-initialize the root module config.Kosygin
"I would end up with hundreds of such calls" - is it that much of a problem?Neva
Thanks @MattSchuchard, will tryRob
I've ended up with "forking" default workspace via cloning tfstate files on GCS. All steps described here: aaabramov.medium.com/…Rob
S
14

The easiest way I know of so far is to create a new state.

For local state...

Delete the local state files

  • .terraform
  • terraform.lock.hcl
  • terraform.tfstate
  • terraform.tfstate.backup

and run terraform init to create a new state.

For (AWS s3) remote state...

Change the backend storage "key" path. For example...

terraform {
  backend "s3" {
    bucket = "terraform-storage"
    key    = "backends/stateX" ###...changed to "backends/stateY"
    region = "us-west-1"
  }
}

...and then run terraform init -reconfigure to create the new state and attach the current project to that state. You can then clean up the old remote state file using whatever method is convenient. Old state files shouldn't interfere with new state files, but best practice is to clean them up anyway.

If you have AWS CLI installed, you can clean up the old state file using a one-liner...

aws s3api delete-object --bucket terraform-storage --key backends/stateX
Stilbite answered 2/2, 2023 at 9:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.