terraformdevopsinfrastructure-as-code

How to properly reset/fork Terraform default tfstate?


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?


Solution

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

    For local state...

    Delete the local state files

    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