How to Create DynamoDB Table using Terraform

How to Create DynamoDB Table using Terraform

How to Create DynamoDB Table using Terraform with Example

In one of my previous posts, I explained how to create DynamoDB table using CloudFormation template. Today we’ll learn to create a DynamodDB table using Terraform.

Before we get into the details, let’s try to understand what is Terraform and DynamoDB. And, how do you create a DynamoDB table resource on AWS using Terraform?

What is Terraform?

Terraform is a popular open-source Infrastructure as Code(IaC) tool by HashiCorp. It lets you provision your infrastructure as code.

  • It lets you provision, update and version your infrastructure in an efficient manner
  • You declare your required infrastructure in a configuration file and Terraform creates it in the correct order.
  • Configuration files are in a human-readable format using HashiCorp Configuration Language(HCL) or even JSON is supported.
  • Terraform is Cloud Agnostic and supports numerous cloud providers like AWS, Azure, GCP etc.

Amazon DynamoDB

Amazon DynamoDB is a fully managed NoSQL database provided by Amazon Web Services. It provides single-digit millisecond performance at any scale. Amazing right?

Of course, it is…

You can choose DynamoDB when you have the requirement to store semi-structured data and retrieve them really fast.

How Do You Create a Resource Using Terraform on AWS?

Unlike CloudFormation, you need to install Terraform in your system before you can use it to create a resource like a DynamoDB table on your cloud provider(In our case AWS).

Once installed, you create your configuration file(filename.tf – they have .tf extension), and use the below set of commands to deploy your resources.

$ terraform init
$ terraform plan
$ terraform apply
$ terraform destroy

I highly recommend you check my step-by-step guide to help you get started with Terraform on AWS in the right way. Here is the link-

Once you go through that post you will already have an idea on-

  • Installing Terraform
  • Creating a Terraform IAM user
  • Setting up AWS CLI to allow Terraform to authenticate to AWS
  • Setting up your workspace using Visual Studio Code(VS Code) IDE
  • Deploying Your First Resource on AWS using Terraform

By this time, I assume you already know how to deploy a resource on AWS using Terraform.

Alright, let’s get started with DynamoDB table creation.

Prerequisite:

How to Create DynamoDB Table using Terraform

In this article, we’ll create a very simple DynamoDB table using Terraform. Later, in this tutorial, we will update our table to switch billing mode to on-demand, and add a range key to it.

Before we start, let me tell you that, to create a DynamoDB table using Terraform, you will need an aws_dynamodb_table resource. Feel free to refer official documentation for up-to-date properties.

Here is what a simple DynamoDB resource looks like-

resource "aws_dynamodb_table" "basic-dynamodb-table" {
  name           = "Employee"
  billing_mode   = "PAY_PER_REQUEST"
  hash_key       = "EmployeeId"

  attribute {
    name = "EmployeeId"
    type = "S"
  }

}

  • name: it’s the name of the table that you provide and is mandatory. name of the table is unique in a region.
  • billing_mode: governs how you are charged for read and write throughput and how capacity is managed. Only PROVISIONED and PAY_PER_REQUEST value is allowed.
  • PROVISIONED: In the case of provisioned, you provide read and write capacity as well
  • PAY_PER_REQUEST: it is on demand and you need not manage anything here. you are charged based on actual uses.
  • hash_key: is the primary key of the table and is required. the hash key must also be the part of attribute as you see in the configuration file above.
  • attribute: all the hash key, and range key must be present as attributes including the ones in Global Secondary Index.

Steps to Create an S3 Bucket using Terraform

  1. Create a Working Directory/Folder
  2. Create your Bucket Configuration File
  3. Initialize Your Directory to Download AWS Plugins
  4. Plan and Deploy
  5. Validate

Step 1: Create a Working Directory/Folder

Create a folder in which you will keep your DynamoDB table terraform configuration file.

Step 2: Create your Table Configuration File

Navigate inside the folder and create your table configuration file. You can name it as per your wish, but to keep things simple, I will name it main.tf

I have started with just provider declaration and one simple resource to create a table as shown below-

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }

  required_version = ">= 0.14.9"
}

#Provider profile and region in which all the resources will create
provider "aws" {
  profile = "default"
  region  = "ap-south-1"
}

#Resource to create dynamodb table 
resource "aws_dynamodb_table" "basic-dynamodb-table" {
  name           = "Employee"
  billing_mode   = "PROVISIONED"
  read_capacity  = 5
  write_capacity = 5
  hash_key       = "EmployeeId"

  attribute {
    name = "EmployeeId"
    type = "S"
  }

  tags = {
    Name        = "Dynamo-DB-Table"
    Environment = "Dev"
  }
}

Copy the above content and save it into a file with .tf extension. You can name as per your wish it main.tf conventionally as well.

Note: In the configuration file above. If you notice, instead of hardcoding credentials in the provider, I am using a CLI profile. This way is more secure to authenticate to AWS. Wanna know why? Read this

#Provider profile and region in which all the resources will create
provider "aws" {
  profile = "default"
  region  = "ap-south-1"
}

Step 3: Initialize Your Directory to Download AWS Plugins

You only do this step once per folder/directory. This basically means you are downloading relevant codes/plugins for your mentioned provider which in our case is AWS.

terraform init
How to Create DynamoDB Table using Terraform 1

Step 4: Plan and Deploy

The configuration file is created and the directory is initialized. That means we are all ready to deploy our DynamoDB table.

Now, if you want, you can run the command terraform plan to see what’s actually being created.

terraform plan

terraform plan
How to Create DynamoDB Table using Terraform 2

Ideally, it shows what is going to be created once you run apply. So in case you see something unintentional, you can review your template and correct it.

terraform apply

terraform apply

Once you are ready to create the resource on AWS, type terraform apply and hit enter.

The prompt asks you – Do you want to perform these actions?

Type yes and hit enter.

If everything is well, your resource is created and you see success message as seen below-

Behind the scene:

Ideally, terraform runs terraform plan every time you hit the command terraform apply. Once you review the plan and confirm yes then only resources will be created.

Terraform looks for .tf file and shows you what’s being created.

Review the output and if all is fine say yes to the prompt.

Once you confirm, terraform starts creating your resource and in a matter of seconds, your table is created.

Step 5: Validate

Login to AWS Management Console and navigate to DynamoDB. Validate your table and it’s setting. This is what it looks like for our use case.

How to Create DynamoDB Table using Terraform 4

By now, we have successfully created a DynamoDB table using Terraform on AWS.

Let’s see how to update the table settings.

Update a Resource using Terraform

You might have questions like, well we created a table but what if we want to update the setting? For example we want to add a range key to the table or we want to change the billing mode.

How do we do it?

Well, it’s very simple, my friend. Update the configuration file with desired settings and run terraform apply once more.

And that’s it- if your setting is correct- your table will be updated with these.

DynamoDB table using Terraform with On-Demand Billing – Example

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }

  required_version = ">= 0.14.9"
}

#Provider profile and region in which all the resources will create
provider "aws" {
  profile = "default"
  region  = "ap-south-1"
}

#Resource to create dynamodb table 
resource "aws_dynamodb_table" "demo-dynamodb-table" {
  name           = "Employee"
  billing_mode   = "PAY_PER_REQUEST"
  hash_key       = "EmployeeId"
  range_key      = "Department"

  attribute {
    name = "EmployeeId"
    type = "S"
  }

  attribute {
    name = "Department"
    type = "S"
  }

  tags = {
    Name        = "Dynamo-DB-Table"
    Environment = "Dev"
  }
}

If you notice the configuration file, we have added two new things here.

  1. Billing Mode
  2. A Range Key

Once the changes are deployed, you can see that it’s reflected on the table.

update dynamodb table using terraform

Clean Up

Finally, if you are doing this exercise for learning purposes, you can clean up by destroying the created resource or DynamoDB table.

terraform destroy
How to Create DynamoDB Table using Terraform 5

Conclusion

In this article, we learnt How to Create DynamoDB Table using Terraform.

Firstly, we learnt how to create any resource using Terraform then we learnt a bit about DynamoDB.

Secondly, we created a configuration file to create a DynamoDB table with one primary key/hash key using Terraform. Later we updated the configuration to add a range key and changed the billing mode. That way, we learnt to update the table settings.

Finally, we learnt to destroy everything and delete the table we created, so that we are not billed unnecessarily.

Well, that was my take on “How to Create DynamoDB Table using Terraform“. Please feel free to share your feedback.

Enjoyed the content?

Subscribe to our newsletter below to get awesome AWS learning materials delivered straight to your inbox.

If you liked reading my post, motivate me by

  • Adding a comment below on what you liked and what can be improved.
  • Follow us on
  • Share this post with your friends and colleagues.

Suggested Read:

Leave a Reply

Your email address will not be published. Required fields are marked *