Terraform Tutorial — Troubleshooting Practice Exercises
Practice diagnosing and fixing common Terraform errors.
Exercise 1: Credential Error
Task: You see Error: No valid credential sources found. List three methods to fix this.
Answer
- Run
aws configureand enter your access key and secret key - Set environment variables:
export AWS_ACCESS_KEY_ID=...andexport AWS_SECRET_ACCESS_KEY=... - Set the profile:
export AWS_PROFILE=my-profile(where the profile is configured in~/.aws/credentials)
Verify with: aws sts get-caller-identity
Exercise 2: Resource Already Exists
Task: You run terraform apply and get BucketAlreadyOwnedByYou. The bucket data-lake-prod exists in your AWS account. Write the commands to bring it under Terraform management.
Answer
- Write the resource block:
resource "aws_s3_bucket" "data_lake" {
bucket = "data-lake-prod"
}
- Import:
$ terraform import aws_s3_bucket.data_lake data-lake-prod
- Plan to align config:
$ terraform plan
- Update config until plan shows no changes.
Exercise 3: Debug Logging
Task: Terraform apply fails with an unhelpful error. Write the commands to enable debug logging and save it to a file.
Answer
$ export TF_LOG=DEBUG
$ export TF_LOG_PATH="terraform-debug.log"
$ terraform apply
# Review the logs
$ grep -i "error" terraform-debug.log
# Clean up when done
$ unset TF_LOG
$ unset TF_LOG_PATH
Exercise 4: State Drift
Task: Someone changed an EC2 instance type from t3.micro to t3.large via the AWS console. terraform plan shows it wants to change it back. What are your two options?
Answer
Option 1: Revert the change — Run terraform apply to change the instance back to t3.micro (what your config says).
Option 2: Accept the change — Update your config to instance_type = "t3.large" and run terraform plan to confirm no changes.
To prevent this in the future, you could restrict console access or add lifecycle { ignore_changes = [instance_type] } if the attribute is managed externally.
Chapter Summary
In this chapter, you learned:
- Credential errors: check with
aws sts get-caller-identity, configure via CLI, env vars, or profiles - Provider errors: version constraints, lock file mismatches, typos
- State drift: detect with
plan, fix withapply(revert) or update config (accept) - Resource exists:
terraform importorimport {}block (TF 1.5+) - Debug logging:
TF_LOG=DEBUG,TF_LOG_PATHfor files,TF_LOG_PROVIDERfor provider-specific
Next up: Practice Projects — five hands-on projects that tie everything together.