Remote State & Best Practices
Configuring Remote Terraform State
When working with Terraform in a team or integrating it into a CI/CD pipeline, multiple team members may execute Terraform commands, leading to state file inconsistencies. To avoid this, configuring remote Terraform state is essential.
A remote backend, such as an S3 bucket, securely stores the Terraform state file, ensuring consistency, backup, and security. To configure this, define a Terraform block in main.tf with the required Terraform version and a backend configuration. The backend specifies the S3 bucket and a key (file path) where the state file (state.tfstate) will be stored. This approach ensures that Terraform state is centrally managed and always accessible.

Create AWS S3 Bucket

When switching to the S3 service, the region setting disappears, defaulting to global. The bucket name must match the reference in Terraform. While configuring the bucket, enabling public access blocking ensures security, allowing access only via AWS credentials.
Bucket versioning is recommended, as it tracks changes similar to Git, maintaining a history of state file modifications. Server-side encryption is automatically enabled, and the bucket key can be disabled if not needed.
The region can be hardcoded since it does not need to match the resource creation region. Once configured, Terraform will store and update the state file in the bucket.
Terraform Best Practices
State Management Best Practices
- Do not manually edit the state file – Always modify the state using Terraform commands to avoid unexpected results.
- Use remote storage for the state file – Store the Terraform state in a shared backend (e.g., S3) so all team members access the latest state.
- Enable state locking – Prevent concurrent updates by enabling state locking (e.g., using DynamoDB with S3).
- Enable state file versioning – Use versioning (e.g., in S3) to track state history and restore previous versions if needed.
- Use separate state files per environment – Maintain dedicated state files for development, testing, and production environments.
Terraform Code Management Best Practices
Store Terraform code in a Git repository – Use Git to collaborate effectively and maintain version history.
- Use a structured review process – Require code reviews and CI pipelines before merging Terraform changes, like application code.
Infrastructure Deployment Best Practices
Automate Terraform execution in CI/CD pipelines – Apply infrastructure changes through automated pipelines instead of running Terraform manually.
These best practices ensure reliable, secure, and scalable Terraform usage across teams. 🚀