how/state
S3 stores the state, DynamoDB holds the lock. What happens when two people run apply at the same time, and why a "team of one" is the only case where you can live without this.
A local terraform.tfstate next to main.tf works fine
while you are alone. The moment a second person joins the team, a
remote backend is mandatory. Without one you either commit the state
to git and edit it inside merge conflicts (a disaster), or you
overwrite each other's changes (a quiet disaster).
The de facto standard on AWS is S3 + DynamoDB:
Press ▶ to walk through the scenario where two people run apply at the same time.
Alice and Bob work with the same infrastructure. They run
terraform apply from their own laptops, but the state is stored not on them,
but in the team's S3 bucket.
DynamoDB is empty for now: nobody is working. The state in S3 has
serial: 10 (that is, 10 successful applies have already been made on it
by someone on the team).
recap
What to remember:
PutItem with the condition "the key does not exist". Whoever gets there first
takes the lock; the second one gets ConditionalCheckFailed and sees
"Lock held by …".terraform apply dies on the network, the lock
stays held until someone runs
terraform force-unlock <LockID>. This is a normal procedure,
not a reason to panic.serial in the state. Before writing, the backend
checks that serial has grown. This is protection against
concurrent overwrites (even without a lock).Next: [[tf-state-mv-rm-import|how to move resources by hand inside the state file]].