Terraform Management of AWS DynamoDB Tables and State Locking

Infrastructure as code transforms how teams provision and operate DynamoDB in AWS. Terraform provides a declarative way to define DynamoDB tables, indexes, streams, and state-locking backends alongside other AWS resources. This approach removes manual console clicks, enables version control, and creates a repeatable configuration harness for production workloads.

Introduction

DynamoDB is a fully managed, serverless NoSQL database service from Amazon Web Services that provides high-performance, scalable, and flexible data storage. It offers features such as automatic scaling, built-in security, and global tables for multi-region, multi-active database capabilities, while eliminating the need for manual server provisioning and management.

DynamoDB is a fully managed service, meaning Amazon handles administrative tasks such as hardware provisioning, setup, configuration, and maintenance. Terraform lets you define your DynamoDB tables and configurations alongside other resources like Lambda functions and API gateways, creating a complete configuration harnessing all the benefits of infrastructure as code for your application.

DynamoDB is one of the most common AWS services managed with Terraform, both as a standalone NoSQL database and as a state-locking backend for the S3 remote backend. In this article, you will learn how to create and manage DynamoDB tables with Terraform, configure Global Secondary Indexes and streams, set up state locking with an S3 backend, and apply production best practices.

Why Use Terraform for DynamoDB

Terraform is an Infrastructure management tool. It facilitates automatically creating cloud resources through resource definition in the files. In the past, manual setup required logging into the cloud provider's console and clicking around to set up servers or databases. Doing it manually like that can be tedious and error-prone. The terraform helps in overcoming this issue by automating the manual setups by defining the tasks and configuring the resources.

Features Of Terraform that facilitate:

  • Terraform Simplifying Infrastructure Deployment: With Terraform, instead of clicking through a UI, you simply write down what you want to build in a description file

When we define AWS resources like a DynamoDB table in our Terraform scripts, Terraform needs a way to actually create these resources by talking to Amazon's servers. It does this through a plugin architecture. The "aws" provider that we configured tells Terraform to download and install a specialized plugin for the Amazon Web Services API. This plugin knows how to translate Terraform resource definitions into real API calls to provision those resources in AWS.

For example, the plugin contains the programming logic to take our DynamoDB table properties and make a CreateTable API request to Amazon behind the scenes to provision that table based on our specifications.

DynamoDB is often used with Terraform for several other reasons:

  • State locking — DynamoDB provides an effective mechanism for state locking in Terraform, which is crucial for preventing concurrent access to the same Terraform state file by multiple users or processes.
  • Scalability and performance — DynamoDB offers high availability, scalability, and low-latency performance, making it an excellent choice for managing Terraform state.
  • Integration with AWS services — DynamoDB is an AWS service, so it integrates seamlessly with other AWS resources that may be part of your infrastructure
  • Managed service — DynamoDB is a fully managed service, which means you don’t have to worry about provisioning, patching, or managing the underlying infrastructure.
  • Flexibility — DynamoDB supports document and key-value data models, providing flexibility in how you store and retrieve data related to your Terraform state.
  • Automatic scaling — DynamoDB can automatically scale to meet the demands of your Terraform operations without manual intervention.

Core DynamoDB Concepts for Terraform Users

What is DynamoDB?

DynamoDB is a fully managed, serverless NoSQL database service from Amazon Web Services that provides high-performance, scalable, and flexible data storage. It offers features such as automatic scaling, built-in security, and global tables for multi-region, multi-active database capabilities, while eliminating the need for manual server provisioning and management.

DynamoDB is a fully managed service, meaning Amazon handles administrative tasks such as hardware provisioning, setup, configuration, and maintenance.

Terraform configuration for DynamoDB centers on the resource aws_dynamodb_table. The table definition includes billing mode, capacity settings, key schema, attributes, tags, and optional secondary indexes and streams.

The following table summarizes key table properties referenced in Terraform configurations:

Property Example Value Description
name UsersTable Table name
billing_mode PROVISIONED Billing mode for capacity
read_capacity 10 Initial read capacity units
write_capacity 5 Initial write capacity units
hash_key userId Primary key partition key
attribute name userId Schema attribute name
attribute type S String data type
tags Name UsersTable Identification tag

Setting Up Terraform for AWS DynamoDB

Follow these steps to create a DynamoDB table using Terraform:

  • Set up AWS credentials.
  • Create a Terraform configuration file.
  • Configure AWS provider

Your file structure should be as shown below. We will use this file to define the provider and connect Terraform to our AWS Account.

Open your main.tf file and the code shown below.

The terraform {} ensures that the current Terraform configuration will use the AWS Provider from the Terraform Registry to manage infrastructure. The provider {} ensures helps configure the specified provider. In this case, we configure the AWS Provider to use the configuration file created by the AWS CLI and to host resources in the Virginia region.

After adding this snippet, launch a terminal in the active directory and run terraform init. It will initialize the configuration directory and install the required provider on your device.

Provider Configuration

In your Terraform configuration file, specify the AWS provider and the region you want to work with:

hcl provider "aws" { region = "us-west-2" # Specify your desired region }

The terraform block and provider block together establish the connection to AWS:

```hcl
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
}

provider "aws" {
region = "us-west-2"
}
```

Defining a DynamoDB Table Resource

Next, add the new DynamoDB table resource to the configuration file. In this example, we will create one called ‘UsersTable’, using the resource awsdynamodbtable.

hcl resource "aws_dynamodb_table" "users" { name = "UsersTable" billing_mode = "PROVISIONED" read_capacity = 10 write_capacity = 5 hash_key = "userId" attribute { name = "userId" type = "S" # String data type } tags = { Name = "UsersTable" } }

Let’s take a look at this basic DynamoDB table in more detail:

  • billingmode is set to PROVISIONED, with read and write capacity units defined. readcapacity and write_capacity specify the initial read and write throughput for the table.
  • hash_key defines the primary key for the table. Here, it’s userId which will be a string type.
  • The attribute block defines the schema for the table. Here, we have only the userId attribute.
  • The tags block assigns a tag named Name to the table for easier identification.

We’ve created our first DynamoDB table in Terraform!

To get the AWS resource name, visit the Terraform AWS Registry. Your DynamoDB table can be set up by adding the configuration below to your main.tf file.

The snippet above shows a simple DynamoDB table declaration. It is defined in the provisioned billing mode, indicating that the table will be provisioned with a pre-defined read, write capacity.

The convention for declaring resources is shown below.

hcl resource "aws_dynamodb_table" "example" { name = "example-table" billing_mode = "PROVISIONED" read_capacity = 5 write_capacity = 5 hash_key = "id" attribute { name = "id" type = "S" } }

Managing Table Items with Terraform

How to manage tables and items using Terraform?

To add items to your existing DynamoDB table, you can use the awsdynamodbtable_item resource.

The resource awsdynamodbtable_item.example is created as part of a scale tutorial. Terraform will perform the following actions:

Plan: 80 to add, 0 to change, 0 to destroy.

Do you want to perform these actions in workspace "learn-terraform-aws-dynamodb-scale"?

Terraform will perform the actions described above.

Only 'yes' will be accepted to approve.

Enter a value: yes

aws_dynamodb_table_item.example["f41f52d4-8431-439b-9dc1-097280edfe9b"]: Creating...

Apply complete! Resources: 80 added, 0 changed, 0 destroyed.

Outputs:
environment_table_arn = "arn:aws:dynamodb:us-east-1:561656980159:table/environment_partially_clearly_polished_moth" environment_table_name = "environment_partially_clearly_polished_moth"

Since global tables are enabled, AWS will automatically propagate this data to your replicas.

Use the AWS CLI to query your DynamoDb table.

The TTL attribute, expiry, is set to a time in the past for 10 of the items in your table, so AWS will automatically delete them. AWS usually removes expired items very quickly. However, occasionally this process can take 48 hours or more.

Plan, Apply, and Validation Workflow

terraform init

Step 7: Terraform Plan

Run the following command to preview the changes.

The "terraform plan" command serves an invaluable purpose - allowing us to preview how Terraform will change our infrastructure before actually applying those changes.

As Terraform beginners, having this insight into what will actually happen is critical for a few reasons:

  • It builds trust. By seeing a readout of the real AWS API calls and resources planned, we verify that Terraform interpreted our config correctly. We can confirm it will make the changes we expect.
  • Allows error checking. If we made a mistake in any resource definitions, the plan output will show discrepancies or failures before any real infrastructure is created

Following along will show you a hands-on example of using Terraform to manage infrastructure as code. The end result will be a DynamoDB table defined in a Terraform config that can be reused and shared.

Terraform lets you define infrastructure like databases as code. This makes it easy to version control and share with others. In this article, I'll walk through the steps to set up a Terraform file and define a DynamoDB table in it. Then I'll apply the plan to create the real table in AWS.

State Locking with DynamoDB and S3 Backend

DynamoDB is one of the most common AWS services managed with Terraform, both as a standalone NoSQL database and as a state-locking backend for the S3 remote backend.

State locking is crucial for preventing concurrent access to the same Terraform state file by multiple users or processes. DynamoDB provides an effective mechanism for state locking in Terraform.

Scalability and performance make DynamoDB an excellent choice for managing Terraform state. DynamoDB offers high availability, scalability, and low-latency performance.

Integration with AWS services is seamless because DynamoDB is an AWS service, so it integrates seamlessly with other AWS resources that may be part of your infrastructure.

The managed nature of DynamoDB means you don’t have to worry about provisioning, patching, or managing the underlying infrastructure.

Flexibility is provided through document and key-value data models, providing flexibility in how you store and retrieve data related to your Terraform state.

Automatic scaling means DynamoDB can automatically scale to meet the demands of your Terraform operations without manual intervention.

Production Best Practices

What we will cover includes configuring Global Secondary Indexes and streams, set up state locking with an S3 backend, and apply production best practices.

Terraform lets you define your DynamoDB tables and configurations alongside other resources like Lambda functions and API gateways, creating a complete configuration harnessing all the benefits of infrastructure as code for your application.

When defining a table, specify billingmode clearly. PROVISIONED mode requires readcapacity and writecapacity. The example UsersTable uses readcapacity 10 and write_capacity 5.

Tag resources consistently using the tags block for easier identification and cost allocation. The example tags block assigns Name = "UsersTable".

Define attribute blocks explicitly for each key attribute with name and type. The example uses type "S" for String data type.

Use terraform plan before apply to preview changes, validate resource interpretation, and catch errors early.

For item seeding at scale, awsdynamodbtableitem can be used with foreach to create many items. The tutorial shows 80 items added with Apply complete! Resources: 80 added, 0 changed, 0 destroyed.

When global tables are enabled, AWS will automatically propagate this data to your replicas.

TTL attributes can be configured for automatic expiration. The TTL attribute, expiry, is set to a time in the past for 10 of the items in your table, so AWS will automatically delete them. AWS usually removes expired items very quickly. However, occasionally this process can take 48 hours or more.

Conclusion

Terraform provides a complete, declarative workflow for provisioning and managing DynamoDB tables in AWS. By defining provider configuration, table schema with billing mode, capacity, hash_key, attributes, and tags, teams gain version-controlled, repeatable infrastructure that integrates with the broader AWS application stack.

State locking with DynamoDB for Terraform S3 remote backends adds safety for collaborative teams, while scalability, managed service characteristics, and automatic scaling ensure the state backend can keep pace with operations.

Managing items with awsdynamodbtable_item enables data seeding as code, and plan validation builds confidence before changes reach production. Combined with global tables for multi-region active-active deployments and TTL for lifecycle management, Terraform-driven DynamoDB delivers high-performance, scalable, and flexible data storage with infrastructure as code governance.

Sources

  1. Source Name
  2. Source Name
  3. Source Name
  4. Source Name

Related Posts