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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Try REST API Generation for MS SQL Server.

DreamFactory generates live REST APIs from database schemas with standardized endpoints for tables, views, and procedures in OpenAPI format. We support on-prem deployment with firewall security and include RBAC for secure, granular security controls.

See more!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay