Creating AWS Remote backend and State Lock with Terraform

Oshaba SamsonOshaba Samson
2 min read

AWS Remote Backend in Terraform refers to using AWS services such as S3 to store and manage Terraform state files remotely. This allows multiple team members to work on infrastructure collaboratively and ensures better security, scalability, and consistency.

Why Use AWS Remote Backend?

  • Collaboration – Multiple engineers can access the same state file.

  • Disaster Recovery – Remote backups ensure state is not lost.

  • State Locking – Prevents simultaneous updates using DynamoDB.

AWS State Locking is a mechanism that prevents simultaneous modifications to the Terraform state file stored in DynamoDB. It ensures that only one Terraform process can modify the state at a time, preventing conflicts and corruption.

Prerequisite

  • AWS Account

  • AWS cli

  • Terraform

To create remote backend and state lock we will create

  • main.tf
provider "aws" {
  region = "us-east-1"
}

resource "aws_s3_bucket" "terraform_s3" {
  bucket = "remote-backend-s3"

  lifecycle {
    prevent_destroy = false
  }
}

resource "aws_s3_bucket_versioning" "terraform_s3" {
  bucket = aws_s3_bucket.terraform_state.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "terraform_s3" {
  bucket = aws_s3_bucket.terraform_state.id

  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}

resource "aws_dynamodb_table" "terraform_locks" {
  name         = "remote-backend-locks"
  billing_mode = "PAY_PER_REQUEST"
  hash_key     = "LockID"

  attribute {
    name = "LockID"
    type = "S"
  }
}
  • outputs.tf
output "s3_bucket_name" {
  value       = aws_s3_bucket.terraform_state.id
  description = "The name of the S3 bucket"
}

output "dynamodb_table_name" {
  value       = aws_dynamodb_table.terraform_locks.id
  description = "The name of the DynamoDB table"
}

To create the resource in aws

  • You need to initialize terraform
terraform init
  • To view resources before creation
terraform plan
  • To create the resources
terraform apply

Then enter yes to confirm

1
Subscribe to my newsletter

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

Written by

Oshaba Samson
Oshaba Samson

I am a software developer with 5 years + experience. I have working on web apps ecommerce, e-learning, hrm web applications and many others