Terraform Tutorial — State Practice Exercises
Practice inspecting, modifying, and managing Terraform state.
Exercise 1: State File Location
Task: You run terraform apply in a project with no backend configuration. Where is the state file stored and what is it called?
Answer
The state file is stored locally in the project directory as terraform.tfstate. A backup of the previous state is saved as terraform.tfstate.backup.
Exercise 2: Rename a Resource
Task: You renamed aws_instance.web to aws_instance.app_server in your .tf file. What command prevents Terraform from destroying the old instance and creating a new one?
Answer
$ terraform state mv aws_instance.web aws_instance.app_server
This updates the state to reflect the new name without touching the real resource.
Exercise 3: Import Existing Resource
Task: Your teammate created an S3 bucket company-logs-bucket manually in the AWS console. Write the steps to bring it under Terraform management.
Answer
- Write the resource block in your
.tffile:
resource "aws_s3_bucket" "logs" {
bucket = "company-logs-bucket"
}
- Import the resource:
$ terraform import aws_s3_bucket.logs company-logs-bucket
- Run plan to see what attributes need to be added:
$ terraform plan
- Update the
.tffile untilterraform planshows no changes.
Exercise 4: State Security
Task: List three reasons why the state file should never be committed to Git.
Answer
- Contains secrets — passwords, API keys, tokens are stored in plaintext
- Concurrency issues — two developers pulling different versions cause conflicts
- Data exposure — anyone with repo access can read sensitive infrastructure details (IPs, ARNs, configurations)
Always use a remote backend with encryption and restrict access through IAM policies.
Chapter Summary
In this chapter, you learned:
- State is a JSON file mapping your config to real cloud resources
- State stores resource IDs, attributes, outputs, and metadata
- Locking prevents concurrent modifications (DynamoDB for S3 backend)
- State commands:
list,show,mv,rm,import,pull,push - Best practices: remote backend, encryption, versioning, never edit manually, never commit to Git
Next up: Workflow — mastering init, plan, apply, and destroy.