How to Create a DynamoDB Table with Terraform
To create a DynamoDB table with
Terraform, use the aws_dynamodb_table resource specifying attributes like name, hash_key, and attribute. Define the table's billing mode and key schema to deploy a fully functional table.Syntax
The aws_dynamodb_table resource defines a DynamoDB table in Terraform. Key parts include:
- name: The table's name.
- hash_key: The primary key attribute name.
- attribute: Defines attribute names and types.
- billing_mode: How you pay for the table (e.g., PAY_PER_REQUEST).
- read_capacity and write_capacity: Used if billing mode is PROVISIONED.
terraform
resource "aws_dynamodb_table" "example" { name = "example-table" billing_mode = "PAY_PER_REQUEST" hash_key = "Id" attribute { name = "Id" type = "S" } }
Example
This example creates a DynamoDB table named example-table with a string primary key Id and uses on-demand billing mode.
terraform
provider "aws" { region = "us-east-1" } resource "aws_dynamodb_table" "example" { name = "example-table" billing_mode = "PAY_PER_REQUEST" hash_key = "Id" attribute { name = "Id" type = "S" } }
Output
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Common Pitfalls
Common mistakes when creating DynamoDB tables with Terraform include:
- Forgetting to define the
attributeblock for thehash_key. - Using
read_capacityandwrite_capacitywithout settingbilling_modetoPROVISIONED. - Not specifying the correct attribute
type(must beS,N, orB).
Example of wrong and right usage:
terraform
# Wrong: Missing attribute block resource "aws_dynamodb_table" "wrong" { name = "wrong-table" billing_mode = "PAY_PER_REQUEST" hash_key = "Id" } # Right: Attribute block included resource "aws_dynamodb_table" "right" { name = "right-table" billing_mode = "PAY_PER_REQUEST" hash_key = "Id" attribute { name = "Id" type = "S" } }
Quick Reference
| Property | Description | Example |
|---|---|---|
| name | Table name | "my-table" |
| hash_key | Primary key attribute name | "Id" |
| attribute | Defines attribute name and type | name = "Id", type = "S" |
| billing_mode | Billing mode: PAY_PER_REQUEST or PROVISIONED | "PAY_PER_REQUEST" |
| read_capacity | Read units (PROVISIONED mode only) | 5 |
| write_capacity | Write units (PROVISIONED mode only) | 5 |
Key Takeaways
Always define the attribute block for the hash key with correct type.
Use PAY_PER_REQUEST billing mode for on-demand capacity without specifying read/write units.
Set read_capacity and write_capacity only if billing_mode is PROVISIONED.
The aws_dynamodb_table resource manages the table lifecycle in Terraform.
Specify the AWS provider and region before creating the table.