Labs · DevOps
Lab: Create a Secure S3 State Bucket, Point a Project at It with use_lockfile, Migrate Local State and See the Lock in Action
Course: DevOps · Chapter 34: Terraform State Remote S3 Backend Locking and Workspaces · Lesson: 34.2 Remote S3 backend with native locking
Chapter 34 explains state, backends, locking and workspaces; this lab sets up the backend every team project needs.
Chala mitrano! State file laptop var asel tar team madhe gondhal. Aaj state S3 madhe, lock sobat.
Suppose we are…
Suppose we are on an Infosys cloud team where two engineers ran terraform apply at the same time from their laptops, each with their own local state. The second apply tried to re-create resources that already existed, and nobody knew which state was correct.
In this lab we keep state in one private, versioned, encrypted S3 bucket, and turn on S3 native locking (use_lockfile = true, Terraform 1.10+), so a second run waits instead of colliding.
Goal of this lab
By the end you will have:
- A bootstrap project that creates the state bucket.
- An app project whose state lives in S3, migrated from local state.
- A second, parallel plan that is blocked by the lock.
What you need
- Terraform 1.10 or newer (S3 native locking).
- AWS CLI v2 signed in to your own AWS account with an IAM user or SSO role that may create these resources (
aws sts get-caller-identityworks). Never use the root user, and never paste access keys into .tf files. - Region Mumbai (
ap-south-1) is used; changeregionif you prefer another. - Two terminal windows. 45 minutes.
Cost and cleanup
The S3 bucket costs a few paise per month. Small charges are possible even on the free tier. Finish the lab in one sitting and always run the Clean up part at the end.
Part 1: Bootstrap the state bucket
Find your account id; it makes the bucket name unique:
aws sts get-caller-identity --query Account --output text mkdir -p tf-state-lab/bootstrap tf-state-lab/app && cd tf-state-lab/bootstrapCreate
bootstrap/main.tf(replace<your-account-id>).force_destroyis only so the lab can clean up:bootstrap/main.tf
terraform { required_version = ">= 1.6" required_providers { aws = { source = "hashicorp/aws" version = "~> 5.0" } } } provider "aws" { region = "ap-south-1" } resource "aws_s3_bucket" "tfstate" { bucket = "badge-tfstate-<your-account-id>" force_destroy = true # lab only } resource "aws_s3_bucket_versioning" "tfstate" { bucket = aws_s3_bucket.tfstate.id versioning_configuration { status = "Enabled" } } resource "aws_s3_bucket_server_side_encryption_configuration" "tfstate" { bucket = aws_s3_bucket.tfstate.id rule { apply_server_side_encryption_by_default { sse_algorithm = "aws:kms" } } } resource "aws_s3_bucket_public_access_block" "tfstate" { bucket = aws_s3_bucket.tfstate.id block_public_acls = true block_public_policy = true ignore_public_acls = true restrict_public_buckets = true }Apply it once:
terraform init terraform applyWhat you should see:
Apply complete! Resources: 4 added.
Part 2: An app project, first with local state
In
../appcreatemain.tfwith a free built-in resource so the lab costs nothing:app/main.tf
terraform { required_version = ">= 1.10" } resource "terraform_data" "release" { input = "badge-api v1" } output "release" { value = terraform_data.release.output }cd ../appApply with local state and save the resource list:
terraform init terraform apply -auto-approve terraform state list > before.txt ls terraform.tfstateWhat you should see: a local
terraform.tfstatefile.
Part 3: Migrate to S3
Add
app/backend.tf(same bucket name as Part 1):app/backend.tf
terraform { backend "s3" { bucket = "badge-tfstate-<your-account-id>" key = "badge-api/dev/terraform.tfstate" region = "ap-south-1" encrypt = true use_lockfile = true } }Migrate and compare:
terraform init -migrate-state terraform state list > after.txt diff before.txt after.txt && echo "same resources" terraform planWhat you should see: answer
yesto copy the state; thensame resourcesandNo changes. Your infrastructure matches the configuration.Check the object in S3 and remove the old local copies:
aws s3 ls s3://badge-tfstate-<your-account-id>/badge-api/dev/ rm -f terraform.tfstate terraform.tfstate.backupWhat you should see:
terraform.tfstatelisted in the bucket.
Part 4: See the lock
Change
inputto"badge-api v2". In terminal 1 run apply and do not answer yet:terraform applyIn terminal 2, in the same folder, run a plan:
terraform plan -lock-timeout=0sWhat you should see: the lock stops the second run (the lesson shows the same error from a Jenkins agent):
Error: Error acquiring the state lock Error message: operation error S3: PutObject, https response error StatusCode: 412, PreconditionFailed Lock Info: ID: 3f2a... Path: badge-tfstate-.../badge-api/dev/terraform.tfstate Who: jenkins@build-agent Operation: OperationTypeApplyAnswer
yesin terminal 1, then run the plan in terminal 2 again.What you should see: it now works and shows
No changes.
Clean up: destroy everything
Destroy the app resource first (its state is in S3), then the bootstrap bucket:
terraform destroy -auto-approve cd ../bootstrap terraform destroyWhat you should see:
Destroy complete!in both folders.force_destroylets Terraform empty the versioned bucket.
Ravindra Bagale's Tip
Keep the state bucket in its own small project and never destroy it in a real team. One bucket, one key per project and environment.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Terraform older than 1.10 | Unsupported argument use_lockfile | Upgrade, or use the older DynamoDB lock table (lesson 34.3) |
| Backend bucket does not exist yet | S3 bucket ... does not exist | Apply the bootstrap project first |
| Using variables in the backend block | Variables may not be used here | Hard-code values or use -backend-config |
Running force-unlock while someone is applying | Two applies at once | Only unlock after checking the run is really dead |
Self-check checklist
0 of 4 done
Try-at-home challenge
Create a workspace with terraform workspace new stage, apply, and find where its state goes in the bucket (env:/stage/...). Then explain when separate folders are better than workspaces.
Samajla ka? One shared state, one lock, no collisions. Aata pudhe jaauya modules.