Terraform Refresh

Terraform’s state file is the single source of truth for your infrastructure. However, the actual state of resources in the cloud can sometimes drift from what’s recorded in the state file. The terraform refresh command helps you synchronize the state file with the real-world state of your infrastructure, ensuring accuracy for your next operations.

Why Use terraform refresh?

  • Detects and updates the state file to match real-world resource states.
  • Identifies drift between your configuration and the deployed infrastructure.
  • Ensures future plans and applies are based on the current infrastructure state.

How to Use It?

  • To refresh the state file: Run terraform refresh. This checks the current state of all resources and updates the state file.
  • To refresh a specific state file: Use the -state flag, e.g., terraform refresh -state=example.tfstate.

Example: Refreshing Terraform State

Imagine you’ve deployed an EC2 instance using Terraform, but someone manually updated the instance type outside of Terraform. To synchronize the state file with the actual infrastructure, run:

terraform refresh

If the EC2 instance type was changed from t2.micro to t3.medium, Terraform will update the state file and display:

Refreshing Terraform state in-memory prior to plan...

aws_instance.example: Refreshing state... [id=i-0abcd1234efgh5678]

Outputs:

instance_type = "t3.medium"

This ensures that future operations like terraform plan and terraform apply reflect the current reality of your infrastructure.

Use Case

Imagine you’re troubleshooting a deployment issue and suspect changes were made manually outside of Terraform. Running terraform refresh updates your state file to accurately reflect the actual infrastructure, providing clarity for the next steps.

Conclusion

The terraform refresh command is essential for maintaining the integrity of your Terraform state file. By ensuring your state file matches the real-world state of your infrastructure, it helps you avoid surprises and ensures accurate planning and deployment.