AWS DynamoDB is a fully managed, serverless, key-value NoSQL database that supports a wide variety of use cases. AWS provides many configuration options to manage DynamoDB tables' capacity and performance. Terraform can be used to configure these options as code.
This article covers the aws_dynamodb_table Terraform resource, how it is provisioned, how capacity and scale features are managed with Terraform, and how tables and items are loaded and referenced. The workflow described applies to both Terraform Community Edition and HCP Terraform. HCP Terraform is a platform that can be used to manage and execute Terraform projects. It includes features like remote state and execution, structured plan output, workspace resource summaries, and more.
The tutorial assumes familiarity with the Terraform and HCP Terraform workflows. If you are new to Terraform, complete the Get Started tutorials first.
Provider and Configuration Foundation
Before a DynamoDB table can be declared, the AWS provider must be configured in Terraform.
hcl
provider "aws" {
region = "us-west-2" # Specify your desired region
}
The provider block configures the specified provider. In this case the AWS Provider is configured to use the configuration file created by the AWS CLI and to host resources in a region.
The terraform block ensures that the current Terraform configuration will use the AWS Provider from the Terraform Registry to manage infrastructure.
File structure is typically organized around a main.tf file that defines the provider and connects Terraform to the AWS Account.
Initialization is performed with:
bash
terraform init
terraform init initializes the configuration directory and installs the required provider on the device.
Declaring awsdynamodbtable
Terraform lets you define infrastructure like databases as code. This makes it easy to version control and share with others. Declaring resources is done by defining a resource block with the type and name.
The convention for declaring resources is shown in the Terraform AWS Registry. The DynamoDB table resource is aws_dynamodb_table.
A minimal example creates a table called UsersTable:
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"
}
}
Resource Attributes
The basic DynamoDB table declaration can be broken down as follows:
billing_modeis set to PROVISIONED, with read and write capacity units defined.read_capacityandwrite_capacityspecify the initial read and write throughput for the table.hash_keydefines the primary key for the table. Here it is userId which will be a string type.- The
attributeblock defines the schema for the table. Here we have only the userId attribute. - The
tagsblock assigns a tag named Name to the table for easier identification.
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.
A table overview can be summarized as:
| Attribute | Value in Example | Purpose |
|---|---|---|
| name | UsersTable | Table name |
| billing_mode | PROVISIONED | Billing mode |
| read_capacity | 10 | Initial RCUs |
| write_capacity | 5 | Initial WCUs |
| hash_key | userId | Primary key name |
| attribute name | userId | Attribute name |
| attribute type | S | String data type |
| tags Name | UsersTable | Identification tag |
Terraform is an Infrastructure management tool. It facilitates automatically creating cloud resources through resource definition in files. In the past, I would log into my cloud provider's console and click around to set up things like servers or databases. Doing it manually like that can be tedious and error-prone though. Terraform helps in overcoming this issue by automating the manual setups by defining the tasks and configuring the resources.
Features of Terraform that facilitate this include:
- 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
Managing Scale and Capacity with Terraform
In this tutorial, you will learn how to configure options with Terraform. First you will provision a DynamoDB table. Next you will use Terraform to configure features that help you manage DynamoDB scale and capacity. Then you will use Terraform to load data into your table, and query the data with the AWS CLI.
Scale related changes are applied as in-place updates. An example plan output shows:
aws_dynamodb_table.environment: Refreshing state... [id=environment_partially_clearly_polished_moth]
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with symbols:
~ update in-place
The plan shows:
~ resource "aws_dynamodb_table" "environment" {
id = "environment_partially_clearly_polished_moth"
name = "environment_partially_clearly_polished_moth"
~ stream_enabled = false -> true
+ stream_view_type = "NEW_AND_OLD_IMAGES"
tags = {}
# (7 unchanged attributes hidden)
+ replica {
+ kms_key_arn = (known after apply)
+ region_name = "ap-northeast-1"
}
+ replica {
+ kms_key_arn = (known after apply)
+ region_name = "us-west-1"
}
# (8 unchanged blocks hidden)
}
Plan: 0 to add, 1 to change, 0 to destroy.
The example shows streamenabled changing from false to true, streamviewtype being added as NEWANDOLDIMAGES, and replicas being added for ap-northeast-1 and us-west-1 with kmskeyarn known after apply.
Execution proceeds with modifying messages:
aws_dynamodb_table.environment: Modifying... [id=environment_partially_clearly_polished_moth]
aws_dynamodb_table.environment: Still modifying... [id=environment_partially_clearly_polished_moth, 10s elapsed]
aws_dynamodb_table.environment: Still modifying... [id=environment_partially_clearly_polished_moth, 20s elapsed]
You can complete this tutorial using the same workflow with either Terraform Community Edition or HCP Terraform.
Loading Data and Table Items
How to manage tables and items using Terraform?
To add items to your existing DynamoDB table, you can use the aws_dynamodb_table_item resource. You can then apply these configurations with Terraform commands terraform init, terraform plan, terraform apply to create, update, and manage DynamoDB tables and their items.
Example item resource:
hcl
resource "aws_dynamodb_table_item" "user_item" {
table_name = aws_dynamodb_table.users.name
hash_key = "userId"
item = jsonencode({
"userId" = { "S" = "user123" }
"UserName" = { "S" = "Luke Skywalker" }
"Email" = { "S" = "[email protected]" }
})
}
Items can be referenced with data sources:
hcl
data "aws_dynamodb_table" "users" {
name = "UsersTable"
}
hcl
data "aws_dynamodb_table_item" "user_item" {
table_name = data.aws_dynamodb_table.users.name
key = jsonencode({
"userId" = { "S" = "user123" }
})
}
aws_dynamodb_table provides details about a specific Dynamodb Table. A minimal configuration to get started is shown with data source usage.
hcl
data "aws_dynamodb_table" "example" {
# Required arguments
# Refer to the Terraform Registry docs for details
}
To remove tables and items from DynamoDB, you can simply remove them from your configuration files and run terraform apply. As they no longer exist in the configuration, they will be destroyed.
How do you prevent destroy in Terraform DynamoDB table?
To prevent the destruction of resources managed by Terraform, particularly DynamoDB tables, you can use the prevent_destroy lifecycle rule within your Terraform code.
Common Workflow Steps
The end result will be a DynamoDB table defined in a Terraform config that can be reused and shared.
Typical steps:
- Define provider and region
- Declare
aws_dynamodb_tablewith name, billing mode, capacity, keys, attributes, tags - Run
terraform init - Run
terraform plan - Run
terraform apply - Optionally declare
aws_dynamodb_table_itemfor seed data - Use data sources to read table and item information
Conclusion
The aws_dynamodb_table resource provides a code-driven way to provision DynamoDB tables and manage capacity and scale features with Terraform. The resource supports provisioned billing mode with explicit readcapacity and writecapacity settings, hash key definition via the attribute block, tagging for identification, and lifecycle operations through standard Terraform commands.
Scale management is expressed as in-place updates to properties such as streamenabled, streamview_type, and replica blocks, with plans showing modifications and apply operations reporting modifying states over time. Data loading is handled via aws_dynamodb_table_item, and existing tables and items can be referenced with data sources aws_dynamodb_table and aws_dynamodb_table_item.
Because Terraform defines infrastructure as code, tables can be version controlled, shared, and reproduced across environments. The workflow works with Terraform Community Edition and HCP Terraform, with HCP providing remote state and execution, structured plan output, and workspace resource summaries.