DynamoDB table for state locking and consistency checking on terraform

2 min read | by Jordi Prats

When using a remote terraform state with S3, it is recomended to use a dynamoDB table for:

  • State locking: Ensures the terrafrom state it is not being modified by two threads at the same time
  • Consistency checking: Makes sure that that terraform it's being used it is the one that it is expected to be used

For example:

terraform {
  backend "s3" {
    bucket         = "infra-tfstate"
    key            = "jenkins/terraform.tfstate"
    region         = "eu-west-1"
    dynamodb_table = "terraform_locks"

With the dynamodb_table keyword we are telling terraform which table it should be using. If we take a look at the contents of the table we will see that it contains a LockID and a digest:

  • LockID: It's a string with the following format: /-md5
  • digest: A MD5 of the terraform state

For example, let's assume we have a record like this one:

infra-tfstate/jenkins/terraform.tfstate-md5 1f36881ca3ea1d2947748d94cf0048ad

If we clone the contents of the S3 bucket:

rclone sync s3:/infra-tfstate/jenkins .

And run a md5sum on the terraform.tfstate file we will get the same value we have on the DynamoDB table

$ md5sum terraform.tfstate 
1f36881ca3ea1d2947748d94cf0048ad  terraform.tfstate

Posted on 08/04/2021