Why does terraform plan lock the state?

Viewed 515

Q: What's the point for the terraform plan operation to lock the state by default?

(I know it might be disabled with -lock=false)

Context:

  • (As far as I understand) The plan operation is not supposed to alter state.
  • plan does start with some version of refresh (which typically alters state), but even the standard output of terraform plan pro-actively says it's not the case with the plan-initiated refresh:
    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.
  • I saw this question on the Hashicorp website, which doesn't seem to provide a conclusive answer.
1 Answers

I believe it is because behind the scenes it performs a state refresh:

-refresh=false - Disables the default behavior of synchronizing the Terraform state with remote objects before checking for configuration changes.

https://www.terraform.io/docs/cli/commands/plan.html

The other reason I can think of is that if you run a plan and someone already locked the state, it means it is performing changes to the state so reading the state might give you a plan that is no longer valid after the lock is freed

https://github.com/hashicorp/terraform/issues/28130

Related