GitOps with Terraform Locking State

Hello,

We use terraform with postgres backend and I would like to use a gitops approch in order to run terraform apply when a pull request is merged to main branch.

I would like to avoid parallel executions (ex: 2 pr are merged). I know that the cli already handle this case by locking the state.

I would like to know if it’s possible to run a command like terraform state status to know before terraform apply if the state is locked or not ? FYI I can access the state as it’s a standalon pg database.

There is no command to check this, but with locks in general, checking is not useful because the lock status may change between the check and operation: Time-of-check to time-of-use - Wikipedia

The locked operations in Terraform do have a -lock-timeout option, which allows terraform to retry the lock. In many cases however it’s better to construct an external locking mechanism to orchestrate the entire workflow, rather than relying on the lock which is intended to only protect the state integrity.

what if I try to take the same lock ?

Terraform will report that the state is locked, either immediately, or after the given -lock-timeout has expired.

I meant from outside. Instead of checking the if it’s locked.

Out of curiosity, I see this in the code terraform/client.go at d30314d2b7495aa596812f3a236ce381c7432a3c · hashicorp/terraform · GitHub but I don’t understand how the id is shared across mutiple command lines.

I’m not familiar with the pg storage internals, but the lock ID is to ensure that the terraform process which locked the state is the same one which unlocked it, so there is intentionally no sharing of the id.

Accessing the state externally of course means you have to coordinate yourself with any running instances of terraform, but that might be intermediated by postgrsql itself.

Ok found what I was looking for thanks to the original PRs and documentation.

first PR when postgres was introduced Postgres backend by mars · Pull Request #19070 · hashicorp/terraform · GitHub
why pg_advisory_lock is used instead of transaction lock Switch pg backend to session-level advisory locking by mars · Pull Request #20561 · hashicorp/terraform · GitHub

got all my answers thanks @jbardin