๐Ÿš€ Terraform S3 Native Locking Demo

AKSHAY SIVAKSHAY SIV
2 min read

Managing Terraform state securely and efficiently just got easier! With the release of Terraform v1.10+, you can now leverage native state locking using .tflock files directly in Amazon S3 โ€” no more setting up a DynamoDB table.


๐ŸŽฏ What's New?

Terraform now supports native .tflock files in S3. By simply adding use_lockfile = true to your backend configuration, Terraform handles locking natively:

No DynamoDB. No extra infra. Just a cleaner and simpler workflow.


๐Ÿ”— GitHub Repo: AkshaySiv/terraform-s3-locking-demo

๐Ÿ“ Project Structure

bashCopyEdit.
โ”œโ”€โ”€ main.tf        # Creates a sample S3 bucket
โ”œโ”€โ”€ backend.tf     # S3 backend config with native locking enabled
โ”œโ”€โ”€ variables.tf   # Input variables (region, bucket name)
โ””โ”€โ”€ outputs.tf     # (Optional) Outputs to display bucket details

๐Ÿ› ๏ธ Prerequisites

  • โœ… Terraform v1.10+

  • โœ… S3 bucket must exist beforehand

  • โœ… Versioning must be enabled on the S3 bucket (recommended)


Backend Configuration (backend.tf)

Here, we're configuring the Terraform backend to use S3 for state storage with native locking enabled use_lockfile = true

Note: The specified S3 bucket must be created manually beforehand โ€” Terraform will not create it for you.

terraform {
  backend "s3" {
    bucket        = "akshay-my-terraform-state-bucket"
    key           = "state/terraform.tfstate"
    region        = "us-east-1"
    encrypt       = true
    use_lockfile  = true
  }
}

๐Ÿชฃ Sample Resource (main.tf)

This Terraform block creates an AWS S3 bucket named from the bucket_name variable and tags it with "Name=Terraform S3 Demo" and "Environment=Dev"

resource "aws_s3_bucket" "demo" {
  bucket = var.bucket_name

  tags = {
    Name        = "Terraform S3 Demo"
    Environment = "Dev"
  }
}

โš™๏ธ Initialize & Apply

terraform init
terraform apply

During apply, youโ€™ll notice a .tflock file pop up in your S3 bucket โ€” this file represents the state lock. It will disappear automatically once the plan/apply is complete.


๐Ÿ” Why Native Locking Rocks

  • ๐Ÿšซ No DynamoDB table required

  • โšก Simpler setup

  • ๐Ÿ’ฐ Reduced cost

  • ๐Ÿง˜โ€โ™‚๏ธ Less maintenance overhead


๐Ÿ“˜ References

0
Subscribe to my newsletter

Read articles from AKSHAY SIV directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

AKSHAY SIV
AKSHAY SIV

๐Ÿš€ DevOps Engineer | Cloud Enthusiast | Automation Specialist ๐Ÿ“Œ Sharing insights on DevOps best practices, infrastructure as code, and system reliability.