When decommissioning a service in Terraform, it's crucial to follow a step-by-step process to avoid breaking the Terraform state and plan checks. This guide will walk you through how to safely remove resources while keeping the provider and backend configuration intact until the final step.
Step 1: Remove Service Resources from Terraform Configuration
First, do not delete the entire module folder or main.tf file just yet. Instead, go into the module folder for the service you want to decommission.
Identify the resources specific to the service (e.g., aws_instance, aws_security_group, etc.) in the directory.
Comment out or delete only the resource definitions for the service you want to decommission.
For example:
# resource "aws_instance" "example_service" {
# ami = "ami-12345678"
# instance_type = "t2.micro"
# ...
# }
Step 2: Run Terraform Plan to Validate Changes
terraform plan
Step 3: Commit Your Changes to Your Branch and Open a PR
Step 4: Get Your PR Approved and Deploy the Changes
Step 5: Clean Up Backend Configuration and Workspace (if applicable)
Why Keep the Provider and Backend Configuration Until Now? The backend configuration is how Terraform knows where to store the state of your infrastructure. If you remove the backend configuration too early, Terraform will lose access to the state file, and it won’t be able to track which resources still exist or need to be destroyed. This can lead to orphaned resources that Terraform can no longer manage, increasing the risk of drift in your infrastructure.
The provider configuration is necessary to communicate with your cloud resources. Removing it too soon would break Terraform’s ability to connect to the cloud provider, preventing it from destroying the existing resources properly.
Now that all resources have been destroyed, you can proceed to remove the provider and backend configurations.
Create a new branch (or use the existing one).
Assuming you have previously removed all resource files and are only left with the provider and backend configs, you can proceed to remove those files from the directory along with the directory itself. If this directory has a workspace defined for Terraform Cloud, you can proceed to delete that workspace as well.
Commit your changes to your branch and open a PR.
Get your PR approved and merge the changes.
Summary By following these steps, you'll ensure that the service is decommissioned properly without breaking your Terraform state or plan checks. Always remember to keep the provider and backend configuration in place until after the resources are fully destroyed. Removing these configurations prematurely can cause Terraform to lose access to the state file, resulting in orphaned resources and infrastructure drift that can be challenging to clean up later.