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.
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.