Create DynamoDB Table using CloudFormation Template

Create DynamoDB Table using CloudFormation
Sharing is Caring:

Create DynamoDB Table using CloudFormation

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

If you are new to DynamoDB and you would like me to cover DynamoDB basics in details. Please let me know in comment section. I would happily cover it in my next post.

In this article, you will learn to create DynamoDB table using CloudFormation template.

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.

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 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, iterable and we can also integrate it into a CI/CD pipeline.
  • If you have the template, you can create the same table in different region or multiple environment such as dev, staging, test and Prod within minutes.
  • While creating tables for learning purpose,deleting the stack will clean up all the table 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, it’s 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 console to create our stack.

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

We will be creating a table with 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: Range key is optional and we will skip 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 case of PROVISIONED capacity, we must provide value for ProvisionedThroughput otherwise it will result in 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 in JSON you can head straight to JSON template section.

Template 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 create table access, S3 bucket put access and CloudFormation create Stack access.

By default CloudFormation uses user credential to generate a temporary session to do stack operation.

However, If you assign a service role, CloudFormation will use 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 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 CICD pipeline consider using service role with policy mentioned in official documentation here.

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

Step 3: Login 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 are 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 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 key. It can be in primary key or Global secondary indexes. If you use any non key attribute in definition,it will throw 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.

Conclusion:

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

If you find any issue 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.

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:

Sharing is Caring:

10 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 *