Setting up AWS S3 Backend and DynamoDB Locking with Terraform
- Published on
By default, Terraform stores the state file locally, but this setup is not ideal in multi-user environments. To ensure centralized state management and prevent concurrent updates to the state file, we can configure Terraform to use S3 as a backend and DynamoDB for state locking.
Why Use S3 and DynamoDB?
- S3 Backend - Centralizes your Terraform state across teams.
- DynamoDB Locking - Prevents multiple concurrent updates to the state.
Step-by-Step: Terraform Setup
Step 1: Create the S3 Bucket and DynamoDB Table
First, you’ll need to create an S3 bucket and a DynamoDB table for locking. You can either do this manually via the AWS Console or automate it with Terraform.
Here’s a sample Terraform configuration for setting up the S3 bucket and DynamoDB table:
provider "aws" {
region = "us-east-1"
}
resource "aws_s3_bucket" "terraform_state" {
bucket = "my-terraform-state-bucket"
acl = "private"
versioning {
enabled = true
}
}
resource "aws_dynamodb_table" "terraform_locks" {
name = "terraform-lock-table"
billing_mode = "PAY_PER_REQUEST"
hash_key = "LockID"
attribute {
name = "LockID"
type = "S"
}
}
Step 2: Configure the S3 Backend and DynamoDB Locking
Next, configure Terraform to use the S3 backend and DynamoDB table for locking. In your main.tf or a dedicated backend configuration file, add the following:
terraform {
backend "s3" {
bucket = "my-terraform-state-bucket"
key = "terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-lock-table"
encrypt = true
}
}
Step 3: Initialize Terraform
After adding the backend configuration, initialize your Terraform setup:
terraform init