Eik
Eik

Reputation: 21

How to delete *.tfstate file from backend S3 bucket

I have backend on aws s3 bucket, where I have all my *.tfstate files. When I do

cd terraform/project.foo
terraform destroy

I would like that it will also remove foo.tfstate file from my backend S3 Bucket, but it's not doing so.

Is there any option, to remove needed tfstate file from backend via terraform?

Thank you!

Upvotes: 2

Views: 5025

Answers (2)

Steve Wall
Steve Wall

Reputation: 1932

This can be accomplished using the AWS cli.

  1. Remove the state file specified in the backend.tf file.

    aws s3 rm s3://my-bucket/my-path/terraform.tfstate

  2. Find the LockID of the state file in dynamodb.  

    aws dynamodb scan --table-name <table_name_from_backend_tf_file>

  3. Create a key.json file to be used during the delete.

    { "LockID": { "S": "use result from above scan" } }

  4. Delete the row using the key.json.

    aws dynamodb delete-item \
    --table-name <table_name_from_backend_tf_file>
    --region
    --key file://key.json

Upvotes: 2

Kishore Venkataramanan
Kishore Venkataramanan

Reputation: 7139

This is totally possible if you are using Terraform workspace

I had two workspace default and prod.

I switched to prod workspace and ran terraform destroy

prod workspace - terrafrom destroy command

This is the S3 state file content, post terraform destroy terraform destroy - state file

Once destroyed, switch to default workspace terraform workspace select default

From default workspace run terraform workspace delete prod

terraform workspace destroy

Poof, your state file is completely cleared up

post-delete s3 file

Note: I'm using fish shell with Terraform plugin, terraform workspace gets printed in prompt (represented by arrow )

Upvotes: 1

Related Questions