State locking - Rigth way to use it

I’m currently working in a project with terraform and azure provider. We now store the state in Azure, as recommended here. Sometimes, when the apply fails due some Azure issue, we cannot change the state anymore, the following error shows up:

│ Error: Error acquiring the state lock
│ 
│ Error message: state blob is already locked
│ Lock Info:
│   ID:        <id>
│   Path:      <path>
│   Operation: OperationTypeApply
│   Who:       iago-moreira@R2D2
│   Version:   0.15.0
│   Created:   2021-05-21 16:44:47.672675626 +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.

I usually resolve this issue using terraform force-unlock but as said in the docs, it is not recomended.

If use the unlock is not recomended, what is the best way to solve the locking problem when the apply fails due Azure provider problem?

Azure problem E.g:
Ip conflicts, network card already in use and etc.

Hi @morallito,

Typically Terraform should still release the state lock even if there was an error during plan or apply. I’d only expect errors actually interacting with the backend to result in a “stuck” lock like this. The intended design is that most of the time you don’t need to think about locks at all and instead they only serve to avoid problems if two members of your team happen to coincidentally run Terraform at the same time.

If you can share a little more detail about what situations you’re seeing where a subsequent operation fails with a lock error like this then I’d love to investigate a little further and try to understand what’s going on.