How to Use Terraform Refresh: Update Infrastructure State
Use
terraform refresh to update your Terraform state file by syncing it with the real-world infrastructure. This command checks the current status of resources and updates the state without making changes to the infrastructure.Syntax
The basic syntax of terraform refresh is simple and straightforward. It updates the state file by comparing it with the actual infrastructure.
terraform refresh: Refreshes all resources in the state.-target=resource_address: Optional flag to refresh only specific resources.-input=false: Prevents interactive prompts during refresh.
bash
terraform refresh [-target=resource_address] [-input=false]Example
This example shows how to use terraform refresh to update the state after a manual change in infrastructure.
bash
terraform init terraform refresh
Output
Initializing the backend...
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
...
Refresh complete! Resources: 0 added, 0 changed, 0 destroyed.
Common Pitfalls
Common mistakes when using terraform refresh include:
- Expecting
terraform refreshto change infrastructure. It only updates the state file. - Not running
terraform initbefore refresh, which can cause errors. - Ignoring the need to specify
-targetwhen you want to refresh only certain resources.
Always remember that terraform refresh does not apply changes; use terraform apply for that.
bash
Wrong: terraform refresh Right: terraform init terraform refresh
Quick Reference
Use this quick guide to remember key points about terraform refresh:
| Command | Description |
|---|---|
| terraform refresh | Update state file with real infrastructure status |
| terraform refresh -target=resource | Refresh only specified resource |
| terraform init | Initialize Terraform before refresh |
| terraform apply | Apply changes after refresh if needed |
Key Takeaways
Run terraform init before terraform refresh to avoid errors.
Terraform refresh updates the state file but does not change infrastructure.
Use -target to refresh specific resources only.
After refresh, use terraform apply to make changes if needed.
Terraform refresh helps keep your state file accurate with real infrastructure.