0
0
TerraformHow-ToBeginner · 3 min read

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 attribute block for the hash_key.
  • Using read_capacity and write_capacity without setting billing_mode to PROVISIONED.
  • Not specifying the correct attribute type (must be S, N, or B).

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

PropertyDescriptionExample
nameTable name"my-table"
hash_keyPrimary key attribute name"Id"
attributeDefines attribute name and typename = "Id", type = "S"
billing_modeBilling mode: PAY_PER_REQUEST or PROVISIONED"PAY_PER_REQUEST"
read_capacityRead units (PROVISIONED mode only)5
write_capacityWrite 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.