Today a quick post about deleting resource from Terraform state using
terraform state rm. I had a situation like this several times where someone manually deleted resources from the cloud without removing the code, and terraform couldn’t handle it. Only after deleting the resource state Terraform create the resource again. There are also a few other situations where using
terraform state rm may be useful:
Deleting outdated resources. If you no longer want to manage a certain resource using Terraform. For example, if you have stopped using a particular VM and want to stop managing it with Terraform, you can remove it from the state.
Moving resources to another configuration file or workspace. If you want to move certain resources to another Terraform workspace, you can use terraform state rm to first remove them from the current state and then add them again in the new workspace and new configuration file. This will avoid conflicts in the state.
Fixing state issues, something about I mentioned at the beginning. Sometimes the Terraform state may become corrupted or out of date.
Terraform state rm can be used as a state repair tool by manually removing problematic resources and adding them again.
Terraform state rm
terraform state rm command you can make the state change and the resources remain intact in AWS. At first, I recommend making a backup just in case. You can also do a dry run. You will find an example below:
#backup terraform state pull > backup.tfstate #dry-run terraform state rm -dry-run 'module.s3.module.aws_s3_bucket["my-s3-bucket"].bucket_s3.this' #rm terraform state rm 'module.s3.module.aws_s3_bucket["my-s3-bucket"].bucket_s3.this'
Warning! Good advice. You must be very careful when performing these operations. Therefore, always make a backup before each state manipulation. Thanks to this, you can easily go back to what was before and reverse the changes.
To identify resources you can use the command:
terraform state list
In some cases, some resources may be difficult to remove using Terraform itself, such as resources created by manual actions or resources created outside of Terraform, or when someone has manually deleted resources that other resources depend on. It may sound complicated, but a simple example would be an aviatrix. If someone deletes the instance containing the controller before deleting the resources it manages, he will have a problem with deleting e.g. security group, gateways, etc. resources managed by aviatrix.
Then the quickest way is to manipulate the state using
terraform state rm and manually remove the resources from the cloud.
For more information, see the Terraform documentation Command: state rm | Terraform | HashiCorp Developer
More tips on state manipulation can be found in the article Terraform – Manipulacja Stanem – Refaktoryzacja – Wojciech Lepczyński – DevOps Cloud Architect (lepczynski.it).