DEV Community

Cover image for Terraform Unimport : The Terraform command that does not exist !
Ashiqur Rahman
Ashiqur Rahman

Posted on • Edited on

Terraform Unimport : The Terraform command that does not exist !

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]'  
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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...
Enter fullscreen mode Exit fullscreen mode

Happy Terraforming !

Note: This SO answer i posted recently inspired me to share this here !

If you found this post helpful, CLICK BELOW 👇 Buy Me A Beer

Top comments (0)