uotn
uotn

Reputation: 37

How to keep terraform's state correct when change state file path?

In the version.tf file, stored key in AWS S3 before

terraform {
  required_version = "1.0.10"

  ...

  backend "s3" {
    encrypt        = true
    bucket         = "terraform-bucket"
    key            = "project1/api/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "state-lock"
  }
}

It's in this path

project1/api/

If change the api folder to price-api, also adjust the state key path:

    key            = "project1/price-api/terraform.tfstate"

It will create new resources beside the previous state key. How to avoid the duplicated state occurred if change key name in the version.tf? Or is there a way to sync the state file with S3 file to ensure they are the same status?

Upvotes: 2

Views: 2059

Answers (1)

Martin Atkins
Martin Atkins

Reputation: 74789

terraform init includes some extra functionality to help with migration of your state between two storage locations.

To use it, you must first initialize your working directory with the old configuration, using the current object key where your state snapshot exists today. Run terraform init with no options to activate that, if you haven't already. (If you're working in a directory you've previously used for other operations then it may already be initialized; you could ensure a clean situation by deleting the .terraform subdirectory and everything inside it.)

Once you've seen terraform init complete successfully with the original path, run terraform show to see if Terraform returns the infrastructure you're expecting to see. This will help confirm that you did indeed select the correct current location for the state you want to migrate.

Now, in the same working directory, change your backend "s3" block to include the new path. If you run terraform init now then Terraform will notice that you changed the backend configuration and will ask you to decide between migrating your state or "reconfiguring".

Migrating state here means to have Terraform read the current state snapshot from the old location, and then write it immediately to the new location, and then initialize from there. That matches what you described in your question, so you can choose that option by running terraform init -migrate-state, as mentioned in the prompt from the previous run.

After you do this you may have the same state snapshot in both locations, so I'd recommend to look directly into the corresponding S3 bucket (using normal S3 tools, rather than Terraform) and check to make sure that the new object is present and matches the old one. If so, you can then safely manually delete the old one just to avoid confusion for anyone who might try to work with an older version of your configuration which still refers to the old path.

Upvotes: 5

Related Questions