Manually lock with Consul


I would like to lock a terraform state stored in Consul with a consul command.
I think the command consul lock is designed for this but I am not able to use it.

Can someone give me an example ?


Hi @smutel,

Terraform uses Consul locks to implement state locking. Terraform does this to prevent others from acquiring the lock and potentially corrupting your state during a Terraform run.

Can you clarify what you mean by this? Are you trying to prevent modification to the Terraform state while the “lock” is in place?

Currently terraform is locking the state file during apply.

I need to change the state file manually (to repair some mistake). To achieve this I need to lock the state manually to prevent the gitlab CI to overwrite the state.



Got it. In this case you can use consul lock to establish a lock on on the Terraform state, and then repair the state file manually.

The following example will acquire the lock for the duration the child command is running, which in this case is 10 minutes (sleep 600).

$ consul lock -verbose terraform/state/ sleep 600
Setting up lock at path: terraform/state/.lock
Attempting lock acquisition
Starting handle