0
0
Terraformcloud~5 mins

Why state should not be edited manually in Terraform - Why It Works

Choose your learning style9 modes available
Introduction
Terraform keeps track of your cloud resources in a state file. Editing this file by hand can cause Terraform to lose track of resources or make wrong changes, leading to errors or resource conflicts.
When you want to understand why Terraform manages resources incorrectly after manual changes
When you need to troubleshoot unexpected Terraform apply failures related to state
When you want to avoid corrupting your infrastructure management by manual state edits
When collaborating with a team to keep infrastructure consistent and safe
When automating infrastructure changes and relying on Terraform's accurate state
Commands
This command shows all resources tracked in the Terraform state. It helps you see what Terraform knows about your infrastructure before making changes.
Terminal
terraform state list
Expected OutputExpected
aws_instance.my_server aws_s3_bucket.my_bucket
This command shows what Terraform will change based on the current state and your configuration. It helps you verify changes before applying them.
Terminal
terraform plan
Expected OutputExpected
An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create - destroy Terraform will perform the following actions: # aws_instance.my_server will be created + resource "aws_instance" "my_server" { ... } Plan: 1 to add, 0 to change, 0 to destroy.
This command applies the planned changes to your infrastructure and updates the state file automatically. It ensures Terraform and your real resources stay in sync.
Terminal
terraform apply
Expected OutputExpected
aws_instance.my_server: Creating... aws_instance.my_server: Creation complete after 10s [id=i-1234567890abcdef0] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Key Concept

If you remember nothing else, remember: always let Terraform manage the state file to keep your infrastructure safe and consistent.

Common Mistakes
Manually editing the Terraform state file to fix resource IDs or attributes
This can corrupt the state, causing Terraform to lose track of resources or apply wrong changes, leading to infrastructure errors.
Use Terraform commands like 'terraform state mv' or 'terraform import' to safely update state.
Deleting resources directly in the state file without using Terraform commands
Terraform will still think the resource exists and may try to recreate or fail during apply.
Use 'terraform state rm' to remove resources safely from the state.
Summary
Terraform state file tracks your real infrastructure resources.
'terraform state list' shows resources Terraform manages.
'terraform apply' updates infrastructure and state safely.
Never edit the state file manually; use Terraform commands instead.