How to Prevent Multiple Terraform Apply

How to Prevent Multiple Terraform Apply

When multiple DevOps engineers work on the same Terraform configuration, it’s crucial to prevent simultaneous terraform apply commands to avoid conflicts and infrastructure inconsistencies.

🔹 Solution: Use Terraform State Locking

Terraform state locking ensures that only one person can run terraform apply at a time. This is best achieved using remote backends like:
AWS S3 + DynamoDB
Terraform Cloud

🔹 How to Implement State Locking with AWS S3 & DynamoDB

1️⃣ Create an S3 bucket for state storage:

"aws_s3_bucket" "terraform_state" {
  bucket = "my-terraform-state-bucket"
  versioning {
    enabled = true
  }
}

2️⃣ Create a DynamoDB table for locking:

"aws_dynamodb_table" "terraform_locks" {
  name         = "terraform-state-lock"
  billing_mode = "PAY_PER_REQUEST"
  hash_key     = "LockID"
  attribute {
    name = "LockID"
    type = "S"
  }
}

3️⃣ Configure the backend in Terraform:

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

Now, only one engineer can run terraform apply at a time!