Ravindra BagaleCourses & study guides Track your progress

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

Intermediate45 minTerraform 1.10+ · AWS CLI v2 · An AWS account

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-identity works). Never use the root user, and never paste access keys into .tf files.
  • Region Mumbai (ap-south-1) is used; change region if 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

  1. 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/bootstrap
    
  2. Create bootstrap/main.tf (replace <your-account-id>). force_destroy is 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
    }
    
  3. Apply it once:

    terraform init
    terraform apply
    

    What you should see: Apply complete! Resources: 4 added.

Part 2: An app project, first with local state

  1. In ../app create main.tf with 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 ../app
    
  2. Apply with local state and save the resource list:

    terraform init
    terraform apply -auto-approve
    terraform state list > before.txt
    ls terraform.tfstate
    

    What you should see: a local terraform.tfstate file.

Part 3: Migrate to S3

  1. 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
      }
    }
    
  2. Migrate and compare:

    terraform init -migrate-state
    terraform state list > after.txt
    diff before.txt after.txt && echo "same resources"
    terraform plan
    

    What you should see: answer yes to copy the state; then same resources and No changes. Your infrastructure matches the configuration.

  3. 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.backup
    

    What you should see: terraform.tfstate listed in the bucket.

Part 4: See the lock

  1. Change input to "badge-api v2". In terminal 1 run apply and do not answer yet:

    terraform apply
    
  2. In terminal 2, in the same folder, run a plan:

    terraform plan -lock-timeout=0s
    

    What 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: OperationTypeApply
    
  3. Answer yes in 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

  1. Destroy the app resource first (its state is in S3), then the bootstrap bucket:

    terraform destroy -auto-approve
    cd ../bootstrap
    terraform destroy
    

    What you should see: Destroy complete! in both folders. force_destroy lets 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

MistakeWhat happensFix
Terraform older than 1.10Unsupported argument use_lockfileUpgrade, or use the older DynamoDB lock table (lesson 34.3)
Backend bucket does not exist yetS3 bucket ... does not existApply the bootstrap project first
Using variables in the backend blockVariables may not be used hereHard-code values or use -backend-config
Running force-unlock while someone is applyingTwo applies at onceOnly 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.