When is terraform refresh used?

Viewed 190

I'm currently learning terraform and I come across the command terraform refresh. It seems that it syncs the terraform.tfstate file to changes I did manually (I tried changing EC2 instance type). I found out that terraform plan can identify the drift between current and desired state without updating the tfstate file. Also, running terraform apply automatically updates the tfstate file.

So I was thinking, if there are any drifts detected during terraform plan, I will just update the terraform code to account for them and let terraform apply update the tfstate file. Is there any reason to use terraform refresh independently?

P.S. I'm using terraform v0.15.0

1 Answers

You're correct that terraform refresh is used to update your terraform state file to match the present state--which can drift if resources have been edited outside of terraform.

terraform refresh itself is deprecated, with a note that it can be unsafe in certain situations. The documentation suggests using terraform apply -refresh-only as an alternative, since it prompts for the user to confirm the changes prior to them being persisted.

As to your question of "when is this used?". In my experience, which primarily uses terraform for AWS deployment, we almost never actually run a refresh operation. Terraform automatically checks current state as part of the terraform plan / terraform apply cycle. This may or may not be specific to the AWS provider.

The one scenario where I could see it being important to refresh the state is when the statefile is used as a datasource via a data remote_state_data block. Specifically, if you have intentionally modified the resource and cannot (or haven't yet) updated the terraform markup to reflect the change. In that scenario other terraform modules are reading values from your statefile (as opposed to from the resources themselves)--if your resource and statefile are out of sync then consumers of the statefile would receive inaccurate data.

However in most cases you want your resources to match their terraform representation--so you would terraform apply to bring the resources and state back in alignment with your terraform module.

Related