- "Run terraform init -migrate-state. Terraform will detect the backend change and ask if you want to migrate your existing local state to the new S3 backend. Type yes.
- Verify the local tfstate file is gone or empty (depending on Terraform version/behavior) and check your S3 bucket; you should see the dev/s3/terraform.tfstate object.
- Now, try terraform plan and terraform apply. You'll notice Terraform is now interacting with the remote state. If someone else tries to apply while your apply is running, they will get a lock error from DynamoDB, preventing conflicts."
- State Management Best Practices:
- Always use remote state for teams and production.
- Enable state locking (e.g., DynamoDB with S3 backend).
- Treat state files as sensitive (they contain resource IDs, relationships, and potentially sensitive outputs). Never commit tfstate to Git.
- Enable versioning on your S3 state bucket for history and rollbacks.
- Backup your state periodically (though S3 versioning helps).
- Avoid manual state file modifications. Use terraform state commands for specific advanced operations (e.g., terraform state mv, terraform state rm, terraform import), but understand the implications.
Terraform Commands:
terraform init - Initialize working Directory, download necessary plugins(aws, random id), backend change the state management.
terraform plan - Terraform will analyze your main.tf file and output a plan
terraform apply - execute the script
terraform state list - checks for the instances created
terraform destroy - destroys the instances created.
- Created a bucket “terraform-bukt” in Amazon s3 manually
- Created a table “terraform-lock-table” in Amazon DynamoDB with LockID
- Added the below entry in main.tf locally
terraform {
backend "s3" {
bucket = "terraform-bukt"
key = "terraform/state.tfstate"
# region = "us-east-1"
region = "ap-southeast-2"
dynamodb_table = "terraform-lock-table"
encrypt = true
}
}
4. Executed “terraform init -migrate-state” locally
5. Executed “terraform plan” locally
6. Executed “terraform apply” locally - > state.tfstate has been created inside Amazon bucket7. Dynamo table "terraform-lock-table" shows the LockID entry