0
0
Terraformcloud~30 mins

Terraform state rm for removing resources - Mini Project: Build & Apply

Choose your learning style9 modes available
Terraform state rm for removing resources
📖 Scenario: You are managing cloud infrastructure using Terraform. Sometimes, you need to remove a resource from Terraform's state without deleting the actual resource in the cloud. This helps when you want Terraform to stop managing that resource but keep it running.
🎯 Goal: Learn how to use the terraform state rm command to remove a resource from Terraform's state file safely.
📋 What You'll Learn
Create a Terraform configuration with one AWS S3 bucket resource
Initialize Terraform in the project directory
Add a configuration variable to hold the resource address
Use the terraform state rm command with the resource address to remove it from state
💡 Why This Matters
🌍 Real World
Cloud engineers often need to remove resources from Terraform state to stop managing them without deleting the actual cloud resources. This is useful during migrations or manual changes.
💼 Career
Knowing how to safely manipulate Terraform state is essential for infrastructure as code roles, ensuring smooth operations and avoiding accidental resource deletions.
Progress0 / 4 steps
1
Create a Terraform configuration with an AWS S3 bucket
Create a file named main.tf and write a Terraform resource block for an AWS S3 bucket named example_bucket with the bucket name my-terraform-bucket-12345. Use the resource type aws_s3_bucket and resource name example_bucket.
Terraform
Need a hint?

Use the resource keyword, specify aws_s3_bucket as the type, and example_bucket as the name. Set the bucket attribute to the exact bucket name.

2
Initialize Terraform in the project directory
Run the command terraform init in your terminal to initialize the Terraform working directory and download the AWS provider plugin.
Terraform
Need a hint?

Open your terminal and type terraform init to prepare Terraform for managing your infrastructure.

3
Add a variable to hold the resource address
In the main.tf file, create a Terraform variable named resource_address with the default value set to aws_s3_bucket.example_bucket. This variable will hold the address of the resource you want to remove from the state.
Terraform
Need a hint?

Use the variable block with type = string and set default to the resource address string.

4
Remove the resource from Terraform state using terraform state rm
Use the command terraform state rm ${var.resource_address} in your terminal to remove the AWS S3 bucket resource from Terraform's state file without deleting the actual bucket.
Terraform
Need a hint?

In your terminal, type terraform state rm followed by the variable reference ${var.resource_address} to remove the resource from state.