S1c0r4x
S1c0r4x

Reputation: 107

terraform locked state file s3 solution

I am trying to fix the well known issue with having multiple pipelines and colleagues are running terraform plan and getting the following error:

│ Error: Error acquiring the state lock

I would like to know if there is any source of the possible ways to get rid of this issue so ci/cd and engineers can run plan without needing to wait for a long time until they are able to work.

Even hashicorp is saying to be careful with force unlock there are risks for multiple writes:

Be very careful with this command. If you unlock the state when someone else is holding the lock it could cause multiple writers. Force unlock should only be used to unlock your own lock in the situation where automatic unlocking failed.

Is there a way that we can write the file to the disk before performing the plan ?

Upvotes: 2

Views: 610

Answers (1)

Fcmam5
Fcmam5

Reputation: 6942

The locking is there to protect you. You may run a plan (or apply) with --lock=false:

terraform plan --lock=false

But I wouldn't encourage that as you may lose the benefits of state locking, it's there to protect you from conflicting modifications made to your infrastructure.

You would like to run a terraform plan against the most recent state which is usually written by the very last apply operation you run on your main/master branch.

If the plan takes too long to apply or to run while your engineers are working on different sub-parts of the infrastructure, you would consider a possible refactoring where you break your infrastructure to multiple folders where you run a separate terraform plan/apply for each of them (src), of course this may come with cost of refactoring and moving resources from a state to another.

One other approach is to disable the state refresh on PR pipelines by setting a --refresh=false which is as well not making you take the full advantages of Terraform's state management with diffs and state locking.


And of course, as a last resort for few exceptions where you have a locked state, you may consider running a manual terraform force-unlock [options] LOCK_ID in few exceptions (for example when a plan gets cancelled, or the runner drops connection so it doesn't release the state).

Resources:

Upvotes: 2

Related Questions