Terraform State — a file that stores the current state of your infrastructure: which resources are created, their IDs, dependencies.
Simple analogy: The state file is like a store receipt: Terraform records what it bought (created) and how much it cost (parameters). Without the receipt, it won't know what's already created.
Problems with local state:
Solution — Remote State (S3 + DynamoDB):
1terraform {2 backend "s3" {3 bucket = "my-terraform-state"4 key = "prod/terraform.tfstate"5 region = "us-east-1"6 dynamodb_table = "terraform-locks"7 encrypt = true8 }9}
State Locking (DynamoDB):
terraform apply runs, Terraform locks the state file.Commands for working with state:
1terraform state list # All resources in state2terraform state show aws_instance.web # Resource details3terraform state mv aws_instance.web aws_instance.app # Rename4terraform state rm aws_instance.web # Remove from state (without deleting the resource!)5terraform import aws_instance.web i-12345 # Import existing resource
Best practices: