Interview Infrastructure as Code (Terraform, Ansible)

What is state locking, and why does it matter for teams?

Infrastructure as Code (Terraform, Ansible) · Basic level

Answer

State locking prevents two Terraform runs from writing the same state at the same time. It matters because concurrent applies can corrupt state or make each run act on stale assumptions. In a team, locking is mandatory for safe shared infrastructure changes.

Technical explanation

Locking protects state writes, not the cloud provider itself; it prevents simultaneous Terraform writers.

A stale lock should be force-unlocked only after proving the original run is dead.

Good pipelines also serialize per workspace to avoid fighting over the same backend key.

Keep Terraform's ownership boundary clear: one state should own a resource or field, and other tools should consume published outputs instead of modifying it.

Use fmt, validate, linting, policy checks, plan review, and state locking before production applies.

Design for small blast radius by splitting state around lifecycle, permissions, and recovery boundaries.

Hands-on example

1. Implement remote state and locking for: What is state locking, and why does it matter for teams?

2. Create or use an S3 bucket with versioning, encryption, public access blocked, and least-privilege IAM. Then configure the backend:

terraform {

backend "s3" {

bucket = "company-tfstate-prod"

key = "platform/network/prod.tfstate"

region = "ap-south-1"

encrypt = true

use_lockfile = true

}

}

3. For legacy DynamoDB locking, verify the table has partition key LockID and migrate deliberately because newer S3 locking makes DynamoDB locking deprecated.

4. Open two terminals and start two applies against the same state key; confirm the second run waits or fails on the lock instead of writing concurrently.

5. Recover safely by checking the active process first; only use force-unlock when the original run is definitely dead.

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Infrastructure as Code (Terraform, Ansible) interview questions

← All Infrastructure as Code (Terraform, Ansible) questions