In Terraform, we can manage resources by deleting everything using the rm -rf
command. This technique is acceptable for resources contained within a local folder.
However, this approach cannot manage resources remotely, such as cloud services. The issue is that we cannot manually destroy resources on a virtual machine, as it results in an inconsistent Terraform state file on the localhost. The state file will not register the destroyed instances and will try to access resources that do not exist.
We want to manage modules under Terraform’s control to avoid inconsistencies between real and Terraform views.
We create a simple module with a file called sample_module.txt
under the Terraform management.
resource "local_file" "sample_destroy_file"{ content = "Sample Terraform Module!" filename = "${path.module}/sample_module.txt" }
Lines 1–4: We’ll create a Terraform instance that is sample_module.txt
as follows:
terraform init and terraform apply -auto-approve
.cat sample_module.txt
(as shown in the working example above) to see the instance created.Note:
terraform destroy
is a destructive act, so it is good to useterraform plan
to avoid unnecessary deletions.
A working example after the deletion is given below. Notice how the sample_module.txt
is now missing.
resource "local_file" "sample_module_file"{ content = "Sample Terraform Module!" filename = "${path.module}/sample_module.txt" }
This implementation builds on our previous example (where we created our sample_module
module).
We’ll enter the following command in the terminal to destroy our resource: terraform plan -flag && terraform destroy -auto-approve
.
Finally, we check to see whether sample_module.txt
is destroyed.
Free Resources