Terraform state locking using DynamoDB

user1619524 picture user1619524 · Apr 4, 2017 · Viewed 7.7k times · Source

Our Terraform layout is such that we run Terraform for many aws (100+) accounts, and save Terraform state file remotely to a central S3 bucket.

The new locking feature sounds useful and wish to implement it but I am unsure if I can make use of a central DynamoDB table in the same account as that of our S3 bucket or do I need to create a DynamoDB table in each of the AWS accounts?

Answer

Jirawat Uttayaya picture Jirawat Uttayaya · Aug 5, 2017

To use terraform DynamoDB locking, follow the steps below

1.Create an AWS DynamoDB with terraform to lock the terraform.tfstate.

provider "aws" {
   region = "us-east-2"
}


resource "aws_dynamodb_table" "dynamodb-terraform-lock" {
   name = "terraform-lock"
   hash_key = "LockID"
   read_capacity = 20
   write_capacity = 20

   attribute {
      name = "LockID"
      type = "S"
   }

   tags {
     Name = "Terraform Lock Table"
   }
}

2.Execute terraform to create the DynamoDB table on AWS

terraform apply

Usage Example

1.Use the DynamoDB table to lock terraform.state creation on AWS. As an EC2 example

terraform {
  backend "s3" {
    bucket = "terraform-s3-tfstate"
    region = "us-east-2"
    key = "ec2-example/terraform.tfstate"
    dynamodb_table = "terraform-lock"
    encrypt = true
  }
}

provider "aws" {
  region = "us-east-2"
}

resource "aws_instance" "ec2-example" {
  ami = "ami-a4c7edb2"
  instance_type = "t2.micro"    
}

The dynamodb_table value must match the name of the DynamoDB table we created.

2.Initialize the terraform S3 and DynamoDB backend

terraform init

3.Execute terraform to create EC2 server

terraform apply

To see the code, go to the Github DynamoDB Locking Example