Create DynamoDB Table using CloudFormation Template

Create DynamoDB Table using CloudFormation

Create DynamoDB Table using CloudFormation Template

DynamoDB is a fully managed serverless NoSQL database in the cloud. Basically, It provides single-digit millisecond performance at any scale. It is the best choice when you want to store semi-structured data that needs to be retrieved fast.

In one of my previous posts, I covered how to create a DynamoDB table using the AWS console. In this article, I’ll share how to create a DynamoDB table using CloudFormation template.

Looking for the best course to master AWS CloudFormation? Here is what I used to get myself kickstarted: AWS CloudFormation Master Class

Before we get into details, let’s try to understand what is CloudFormation and why should we bother to create a DynamoDB table using CloudFormation.

Related:

What is CloudFormation?

  • CloudFormation is a tool/service by AWS which allows us to create/manage our entire AWS infrastructure as a code.
  • CloudFormation makes it possible to replicate an application environment easily with a few clicks.
  • We tell what we need in a declarative way in a template and CloudFormation creates them in the correct order.
  • We can use YAML or JSON while describing our resources.

Benefits Of Creating a DynamoDB Table using CloudFormation?

  • Using CloudFormation will make our stack reproducible, and iterable and we can also integrate it into a CI/CD pipeline.
  • If you have the template, you can create the same table in a different region or multiple environments such as dev, staging, test and Prod within minutes.
  • While creating tables for learning purposes, deleting the stack will clean up all the tables and you don’t need to do clean up manually.

Steps required to create a Dynamo DB table using CloudFormation

  1. A template describing the table, its primary key and indexes.
  2. Permission to create a DynamoDB table, to create a CloudFormation stack
  3. CloudFormation console/ AWS CLI or API. In this article, we will be using a console to create our stack.

Step 1: Let’s create a template for our table

We will be creating a table with the below specification

  • Table Name: Employee(If we don’t provide a name, CloudFormation will generate a unique physical Id and use it as a name)
  • Primary/Hash Key: EmployeeId (primary key is mandatory while creating a table, all the items can uniquely be identified by primary/hash key)
  • Range Key: The Range key is optional and we will skip it here
  • BillingMode: PROVISIONED(By default billing mode is PROVISIONED and we need not specify it, however for on-demand capacity use BillingMode: PAY_PER_REQUEST)
  • In the case of PROVISIONED capacity, we must provide value for ProvisionedThroughput otherwise it will result in an error.

You can create a template in template designer or can use the template created below. I have created the template in YAML however if you need it in JSON you can head straight to JSON template section.

Related: How to Convert a CloudFormation Template From JSON to YAML and Vice Versa

CloudFormation Template to Create a DynamoDB table in YAML:

AWSTemplateFormatVersion: 2010-09-09
Description: AWS CloudFormation Template To Create a DynamoDB

Parameters:
  HashKeyElementName:
    Type: String
    Default: EmployeeId
    Description: Hash Key Name
  HashKeyElementType:
    Type: String
    Default: S
    Description: Hash Key Type
Resources:
  EmployeeTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: Employee
      AttributeDefinitions:
        - 
          AttributeName: !Ref HashKeyElementName
          AttributeType: !Ref HashKeyElementType
      KeySchema:
        - 
          AttributeName: !Ref HashKeyElementName
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5 
Outputs:
  Employee:
    Description: Table Created using this template.
    Value: !Ref EmployeeTable

CloudFormation Template to Create a DynamoDB table in JSON:

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "AWS CloudFormation Template To Create a DynamoDB",
    "Parameters": {
        "HashKeyElementName": {
            "Type": "String",
            "Default": "EmployeeId",
            "Description": "Hash Key Name"
        },
        "HashKeyElementType": {
            "Type": "String",
            "Default": "S",
            "Description": "Hash Key Type"
        }
    },
    "Resources": {
        "EmployeeTable": {
            "Type": "AWS::DynamoDB::Table",
            "Properties": {
                "TableName": "Employee",
                "AttributeDefinitions": [
                    {
                        "AttributeName": {
                            "Ref": "HashKeyElementName"
                        },
                        "AttributeType": {
                            "Ref": "HashKeyElementType"
                        }
                    }
                ],
                "KeySchema": [
                    {
                        "AttributeName": {
                            "Ref": "HashKeyElementName"
                        },
                        "KeyType": "HASH"
                    }
                ],
                "ProvisionedThroughput": {
                    "ReadCapacityUnits": 5,
                    "WriteCapacityUnits": 5
                }
            }
        }
    },
    "Outputs": {
        "Employee": {
            "Description": "Table Created using this template.",
            "Value": {
                "Ref": "EmployeeTable"
            }
        }
    }
}


Step 2: Permission to create a Dynamo DB table using CloudFormation.

Whenever you create a CloudFormation stack, please note that CloudFormation can only perform actions that your user/service role has permission to.

To create a DynamoDB table using CloudFormation, you will need DynamoDB to create table access, S3 bucket put access and CloudFormation to create Stack access.

Related: How to Create DynamoDB Table using Terraform

By default, CloudFormation uses user credentials to generate a temporary session to do stack operations.

However, If you assign a service role, CloudFormation will use the service role to perform all stack operations.

I am an administrator user so I need not provide any extra policy however if you are not an admin, apply the below policy to your user.

For simplicity, I have assigned “*” for all the services however always limit this to actions that you will perform(Principle of least privilege)

{
    "Version":"2012-10-17",
    "Statement":[{
        "Effect":"Allow",
        "Action":[
            "s3:*",
            "cloudformation:*",
            "dynamodb:*"
        ],
        "Resource":"*"
    }]
}

Also, If you are creating the table as part of the CICD pipeline consider using the service role with the policy mentioned in the official documentation here.

Once we are done giving proper access to our user or service role, we can proceed to Step 3.

Step 3: Log in to AWS Management Console. Search CloudFormation in the services. Click on Create Stack.

You can either upload the template to an S3 bucket and provide the URL in the bar or you directly upload the template here.

After clicking on Create stack, you can provide a stack name and parameters details like below. Click next, next and a table is created and can be verified in DynamoDB.

Things to Note while creating a Table using CloudFormation

  • In attribute definition, use only parameters that are part of the key. It can be in primary key or Global secondary indexes. If you use any non-key attribute in the definition, it will throw a validation exception.
  • Use BillingMode: PAY_PER_REQUEST while creating a table with on-demand capacity.
  • When using PAY_PER_REQUEST, Property ProvisionedThroughput can’t be used. As only one of them is required to create a table but not both at a time.

Important Note: We created the DynamoDb table with CloudFormation using the console. However, an easier and more effective way is to use AWS CLI. Here is how you can deploy a CloudFormation Template on AWS using CLI.

Conclusion:

We were able to create a DynamoDB table using CloudFormation with ProvisionedThroughput or in other words ReadCapacityUnits /WriteCapacityUnits.

This was a very simple table. Feel free to check more on DynamoDB-

If you find any issues while creating the table, please leave a comment below. I would be happy to help.

Enjoyed the content?

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

Well, That was my take on creating a Dynamodb table using CloudFormation template. If you liked reading my post, you can motivate me by-

  • Adding a comment below on what you liked and what can be improved.
  • Follow us on FacebookTwitterLinkedInInstagram
  • Subscribe to our newsletter to get notified each time we post new content
  • Share this post with your friends

Also Read:

4 thoughts on “Create DynamoDB Table using CloudFormation Template

  1. Hello ,

    Please cover dynamodb as well

    I am new to cloud aws I am following up your blogs its nicely presented ..also further if you have any scenarios of on premise setup as well as cloud migrations will be really really helpful.

    Regards,
    Sandesh

Leave a Reply

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