Initial Resource Creation
Consider the following Terraform configuration:Refreshing State with Terraform Plan
Before generating an execution plan, Terraform refreshes the state by comparing it with the actual state of your external resources. For example, the output of the plan command may look like:Disabling the state refresh is generally not recommended as it may introduce inconsistencies if resources have been manually modified. Use this option with caution, especially in large environments.
Tracking Configuration Changes with the State File
Terraform continuously monitors the state file to detect changes between your configurations and your provisioned resources. For example, if you change the instance type from m5.large to t3.micro, Terraform will detect the discrepancy during the next plan or apply.Original Variable Definitions
After Modifying the Configuration
Managing Resource Dependencies
Terraform also manages inter-resource dependencies using the state file. Consider a configuration where a web instance depends on a DB instance:Security and Remote State Management
The state file contains sensitive information, including configuration variables and resource attributes like SSH keys or initial passwords. Store your state file securely in remote backends (e.g., Amazon S3 or Terraform Cloud) and never commit it to version control systems.
Final Thoughts on Terraform State
Terraform state is designed exclusively for internal Terraform operations. It is essential to avoid manually editing the state file and to use Terraform commands to manage state. The information contained in the state file is crucial, and any changes to the configuration are reflected through Terraform’s plan and apply process. For example, here is a state file entry for a development EC2 instance:Summary
By following these best practices, you can ensure that your Terraform operations are secure, reliable, and accurately reflect your intended infrastructure changes.