CD4: Terraform for teams

Lesson 1 of 5 · reading 15–25 minutes; practice and project time is on the module page

Shared state and locking

🎯You'll be able to

Store state where the whole team and the pipeline can use it, with locking so two applies can't run at once, and protect it properly.

🏠The everyday picture

A shared train reservation chart has one copy, at the station. When a clerk books a seat, they hold the chart until they've written the name, so two clerks can't sell the same seat. If each clerk kept their own chart, double bookings would follow.

📘What it really is

📝A worked example

Input: in the RouteRani kit, run terraform apply -var app_count=3 in one terminal and, while it runs, terraform plan in a second terminal in the same folder.

Expected output: the second command stops with Error acquiring the state lock and shows who holds the lock and since when (the local backend's lock is the file .terraform.tfstate.lock.info). Once the apply finishes, the plan runs. A remote backend does the same thing for everyone on the team and the pipeline.

🌍Where it's used

📝Case scenario

Two engineers at a payments startup applied changes to the same environment within a minute of each other, each from local state on their laptop. The second apply didn't know about the first engineer's new firewall rule and removed it, cutting off a partner bank's connection for an hour. Moving state to an encrypted bucket with locking made the second apply wait.

🖱️Try it

Run the two-terminal example above. Then look at .terraform.tfstate.lock.info while the apply runs (cat infra/.terraform.tfstate.lock.info). Success: you've seen the lock, its ID and who holds it, and the second command waiting.

⚠️Common mistakes

🛠️For your project

The projects use local state on your computer. In your capstone write-up, explain which backend you would use for RouteRani in a team and why.

✅Quick check

What does state locking prevent?

Show the answer

Two plans or applies changing the same state at the same time.

Why turn on versioning for the state bucket?

Show the answer

To restore an earlier state if it's corrupted or overwritten.

← BackCD4
ProLearners Assist