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.
terraform state rm
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[0]'
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.
Bonus
Utilize the -dry-run
flag before performing a potentially destructive operation like this.
terraform state rm 'resource_id' -dry-run
Output:
Acquiring state lock. This may take a few moments...
Would remove module.s3.module.s3_bucket["production-files"].aws_s3_bucket.this[0]
Releasing state lock. This may take a few moments...
Happy Terraforming !
Note: This SO answer i posted recently inspired me to share this here !
Top comments (0)