Terraform import is a great feature to import existing resources into terraform state. But, what if we accidentally imported some resource into terraform state and we want to unimport them again.
Well, terraform does not really have a command/feature that does exactly that but here's one cool trick you can use to quickly unimport some resources from Terraform state.
While running the terraform command to remove a resource from the state, make sure you quote(
') the resource id appropriately like so,
terraform state rm 'module.s3.module.s3_bucket["my-s3-bucket-name"].aws_s3_bucket.this'
Terraform state list can often be very long. If you need to remove a group of resources sharing a common name you can use the following bash oneliner,
terraform state rm $(terraform state list | grep production-files)
For example, the command above will remove a aws_s3_bucket, aws_s3_bucket_policy, aws_s3_bucket_cors_configuration and so on.
-dry-run flag before performing a potentially destructive operation like this.
terraform state rm 'resource_id' -dry-run
Acquiring state lock. This may take a few moments...
Would remove module.s3.module.s3_bucket["production-files"].aws_s3_bucket.this
Releasing state lock. This may take a few moments...
Happy Terraforming !
Note: This SO answer i posted recently inspired me to share this here !