Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

terraform

How to destroy or delete modules in Terraform

Mujtaba Jamil Malik

Overview

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.

Destroying with Terraform

We create a simple module with a file called sample_module.txt under the Terraform management.

Initializing the module

resource "local_file" "sample_destroy_file"{
    content = "Sample Terraform Module!"
    filename = "${path.module}/sample_module.txt"
}

Explanation

  • Lines 1–4: We’ll create a Terraform instance that is sample_module.txt as follows:

    • We’ll navigate to our desired directory and run the following command to create our module: terraform init and terraform apply -auto-approve.
    • We’ll enter the following command: cat sample_module.txt (as shown in the working example above) to see the instance created.
    • Next, we’ll destroy the module.

Note: terraform destroy is a destructive act, so it is good to use terraform plan to avoid unnecessary deletions.

Example

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"
}

Explanation

  • 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.

RELATED TAGS

terraform
RELATED COURSES

View all Courses

Keep Exploring