red888
red888

Reputation: 31642

Can `terraform destroy` delete the S3 state file when destroying?

When I run terraform destroy to destroy everything in a folder I leaves behind the state file in S3 (which I'm using as my backend).

The state file it leaves behind looks like this:

{
  "version": 4,
  "terraform_version": "0.12.12",
  "serial": 7,
  "lineage": "9eb5ca6d-20a9-d5f5-053a-eefe274bf669",
  "outputs": {},
  "resources": []
}

Can Terraform delete the S3 file on destroying?

Upvotes: 6

Views: 7530

Answers (3)

simmyk
simmyk

Reputation: 26

There is no straight forward option to delete a state file we can manipulate it with terraform state rm command.

But One of the way is to use workspace for each environment but default workspace wont be deleted in that case.

Another way would be in aws cli something like aws s3 rm s3://mybucket/foo.tfstate. https://docs.aws.amazon.com/cli/latest/reference/s3/rm.html might help.

Upvotes: 0

Gavin Clarke
Gavin Clarke

Reputation: 389

If you are using terraform workspaces to represent different environments then it is possible to remove the state file for a particular workspace by calling:

terraform workspace select default && terraform workspace delete workspace_for_deletion

This will only work with an empty state so should be called after you call terraform destroy.

Note that the default workspace can't be deleted. This means this isn't a perfect solution, but it should help keep minimise the clutter in your backend.

Upvotes: 2

bishop
bishop

Reputation: 39434

Probably not.

Terraform requires state to function, and a state file with zero resources represents an infrastructure state that's different than having no state file at all. Namely that you've created resources before, and if one were to compare backups of the state file, one could clearly see and restore the state history.

We further confirm this by looking at the terraform state and terraform destroy commands and notice none of their sub-commands or options remove the state file.

Having said that, what may work and I've never tried this, is if terraform manages the bucket containing the state file, and you destroy that bucket (using a local backup as the state file during the bucket destroy operation), we're effectively tricking terraform into erasing its state.

Upvotes: 4

Related Questions