How to handle terraform locks when they are stuck
Terraform state is stored in an S3 backend. This allows our remote, distributed teams to share state.
Terraform automatically downloads the state, modifies it as needed during an apply operation, and then uploads the new version back to S3.
But this introduces a risk that two people attempt to change the state at the same time. To prevent this, terraform also locks the state file.
If a second person attempts any operation that would read or update the state while it is locked, terraform provides a friendly error. This is good.
But occasionally the lock can get stuck, like if someone cancels a terraform command before it has a chance to unlock the state.
When this happens, you get an error like this:
Acquiring state lock. This may take a few moments...
╷
│ Error: Error acquiring the state lock
│
│ Error message: ConditionalCheckFailedException: The conditional request failed
│ Lock Info:
│ ID: 88d70d71-20ca-d968-cc2c-b43399afef96
│ Path: datateer-terraform-remote-state-backend-gps/states/terraform.tfstate
│ Operation: OperationTypeApply
│ Who: adam@DESKTOP-FDV9CQB
│ Version: 1.2.6
│ Created: 2022-12-22 13:20:00.8952173 +0000 UTC
│ Info:
│
│
│ Terraform acquires a state lock to protect the state from being written
│ by multiple users at the same time. Please resolve the issue above and try
│ again. For most commands, you can disable locking with the "-lock=false"
│ flag, but this is not recommended.
If you encounter this error, first be absolutely sure that the lock is stuck and that you should unlock it manually.
Then run the force-unlock command, using the ID from the error message: `terraform force-unlock 88d70d71-20ca-d968-cc2c-b43399afef96`