Skip to main content

Destroying Infrastructure

1. Destroying All Resources

Use the terraform destroy command to remove all resources managed by your Terraform configuration.

Example: Destroying All Resources

terraform destroy
Option Values Description
-auto-approve true Skips interactive approval before destroying resources
-backup <path> Path to backup the current state file before destroying
-dry-run true Simulates the destroy operation without making changes
-force true Forces destruction even if there are errors or dependencies
Note: The terraform destroy command removes all resources defined in your configuration. Ensure you have backups or are certain about the action before proceeding.
Warning: This operation is irreversible. All resources will be deleted permanently.

2. Auto-Approving Destruction

Option Values Notes
-auto-approve true Skips the approval prompt during destroy operations
-auto-approve false Requires manual confirmation before destroying resources (default)

Example: Destroy with auto-approval

terraform destroy -auto-approve
Note: Using -auto-approve bypasses the interactive confirmation step and should be used with caution in production environments.

3. Destroying Specific Resources

Resource Type Identifier Description Action
aws_instance aws_instance.web_server EC2 instance for web server terraform destroy -target=aws_instance.web_server
google_compute_instance google_compute_instance.app_server Compute instance for application server terraform destroy -target=google_compute_instance.app_server
azurerm_resource_group azurerm_resource_group.test_rg Resource group for test environment terraform destroy -target=azurerm_resource_group.test_rg

Example: Destroying a Specific S3 Bucket

resource "aws_s3_bucket" "example_bucket" {
  bucket = "my-example-bucket"
}

Example: Targeted Destruction Command

terraform destroy -target=aws_s3_bucket.example_bucket
Note: Using -target limits destruction to the specified resource and its dependencies. It does not remove other resources from state.
Warning: Destruction with -target can lead to inconsistent state if dependencies are not properly handled. Always verify the plan before proceeding.

4. Generating Destroy Plans

Command Description Flags
terraform plan -destroy Generates a plan to destroy all resources in the current state -out=<filename> to save plan to file
terraform plan -destroy -target=<resource> Destroys only the specified resource or module -target=<resource> to limit scope

Example: Generating a destroy plan

terraform plan -destroy -out=destroy.tfplan
Note: The -out flag saves the plan to a file for later use with terraform apply.
Warning: Destroy plans can be destructive and should be reviewed carefully before applying.

5. Using Variable Files

File Type Description Usage
.tfvars Variable definition files for Terraform Define values for variables declared in variables.tf
.tfvars.json JSON format variable files Use for automation or when JSON is preferred over HCL

Example: Defining Variables in variables.tf

variable &#34;instance_type&#34; {
  description = &#34;Type of EC2 instance to launch&#34;
  type        = string
  default     = &#34;t2.micro&#34;
}

variable &#34;count&#34; {
  description = &#34;Number of instances to launch&#34;
  type        = number
  default     = 1
}

Example: Setting Values in prod.tfvars

instance_type = &#34;t3.large&#34;
count         = 5

Example: Using Variables in main.tf

resource &#34;aws_instance&#34; &#34;web&#34; {
  count         = var.count
  instance_type = var.instance_type
}
Note: Variable files are loaded in order of precedence, with terraform.tfvars having the highest priority.

Workflow: Applying Variables from Files

  1. Create variables.tf with variable declarations
  2. Create .tfvars file with desired values
  3. Run terraform apply -var-file=prod.tfvars

6. Understanding Destroy Order

Note: Terraform destroys resources in the reverse order of creation, based on dependencies. This ensures that dependent resources are destroyed before their dependents.
Resource Type Destroy Order Description
aws_instance Reverse dependency order Instances are destroyed after their dependencies like security groups or EBS volumes.
aws_security_group Reverse dependency order Security groups are destroyed before the instances that use them.
aws_ebs_volume Reverse dependency order EBS volumes are destroyed before the instances that use them.

Example: Destroy Order in Practice

resource "aws_security_group" "web_sg" {
  name = "web-sg"
}

resource "aws_instance" "web_server" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"

  vpc_security_group_ids = [aws_security_group.web_sg.id]
}

resource "aws_ebs_volume" "web_volume" {
  availability_zone = "us-west-2a"
  size              = 20

  attachment {
    instance_id = aws_instance.web_server.id
    device_name = "/dev/sdh"
  }
}

Destroy Order Workflow

  1. Identify all resources in the Terraform state
  2. Determine dependencies between resources using the dependency graph
  3. Sort resources in reverse creation order based on dependencies
  4. Destroy resources starting with the last created and working backwards

Key Points

  • Terraform ensures safe destruction by reversing the creation order
  • Resources with no dependencies are destroyed last
  • Resources with dependencies are destroyed before their dependents

7. Handling Destroy Errors

Error Type Description Handling Strategy
Dependency Conflict Destroy fails due to dependencies on resources that are still in use. Use terraform state list to identify dependencies and remove them manually or adjust resource configuration.
Permission Denied Insufficient permissions to delete resources in the cloud provider. Ensure Terraform has appropriate IAM roles or service account permissions for resource deletion.
Resource Locks Resources are locked by another process or Terraform workspace. Release locks using terraform force-unlock or wait for the lock to expire.
External State Changes State file has been modified externally, causing inconsistency. Use terraform refresh to update state or restore from a backup.

Example: Resolving Dependency Conflicts

terraform state list
terraform state show <resource_id>
terraform state rm <dependent_resource>
Note: Always backup your state file before attempting manual cleanup or force-unlocking.
Warning: Force-unlocking should only be used when you are certain no other Terraform processes are running.

8. Using Parallelism

Example: Setting max parallelism

terraform {
  required_version = "~> 1.0"
  backend "s3" {
    bucket = "my-terraform-state"
    key    = "prod/infrastructure.tfstate"
  }
}

resource "aws_instance" "web" {
  count = 5
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}

# Apply with max 2 concurrent operations
# terraform apply -parallelism=2
Flag Description Default Value Notes
-parallelism=N Limit the number of concurrent operations 10 Useful for resource-constrained environments
Note: The -parallelism flag affects all operations (plan, apply, destroy) and is applied globally to the Terraform run.
Warning: Setting -parallelism too low can significantly increase operation time, especially for large infrastructures.

Parallelism Best Practices

  • Start with default parallelism (10) and adjust based on performance
  • Reduce parallelism in CI/CD pipelines to avoid resource contention
  • Use -parallelism=1 for debugging or when order matters

9. Confirming Destruction

Option Values Description
-auto-approve true Skips interactive approval for destruction operations
-destroy true Explicitly enables destruction mode (used with terraform plan)

Example: Approving Destruction

terraform destroy -auto-approve
Note: Using -auto-approve bypasses the interactive confirmation prompt and should be used with caution in production environments.
Warning: Destruction operations are irreversible. Ensure all backups and state files are secured before proceeding.

10. Preventing Accidental Destruction

Option Values Notes
terraform destroy -auto-approve Skips confirmation prompt
terraform destroy -target=<resource> Destroys only specified resource
terraform destroy -lock=<bool> Locks state during destruction

Example: Using -auto-approve with caution

terraform destroy -auto-approve
Note: Use -auto-approve only in CI/CD pipelines or automated environments where manual confirmation is not feasible.
Warning: Running terraform destroy without targeting specific resources will delete all managed infrastructure.

Best Practices for Safe Destruction

  • Always review the plan before destruction using terraform plan -destroy
  • Use -target to limit scope to specific resources
  • Enable state locking in shared environments
  • Backup state files before destructive operations

Was this article helpful?