Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform state locking using DynamoDB

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?

like image 333
user1619524 Avatar asked Apr 04 '17 14:04

user1619524


2 Answers

You can use a single DynamoDB table to control the locking for the state file for all of the accounts. This would work even if you had multiple S3 buckets to store state in.

The DynamoDB table is keyed on LockID which is set as a bucketName/path. So as long as you have a unique combination of those you will be fine (you should or you have bigger problems with your state management).

Obviously you will need to set up cross account IAM policies to allow users creating things in one account to be able to manage items in DynamoDB.

like image 51
ydaetskcoR Avatar answered Nov 10 '22 04:11

ydaetskcoR


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

like image 38
Jirawat Uttayaya Avatar answered Nov 10 '22 04:11

Jirawat Uttayaya