DynamoDB knowledge portalHow do I create a table with CloudFormation?2 min

Creating a template

Creating a DynamoDB table with CloudFormation involves defining a template YAML or JSON file that specifies the properties for your AWS resources. The YAML example below creates a table with an attribute ("id") as its partition key and attribute (“date”) as its sort key:

Resources:
  MyDynamoDBTable:
    Type: 'AWS::DynamoDB::Table'
    Properties:
    TableName: 'MyTable'
    AttributeDefinitions:

    AttributeName: 'id'
    AttributeType: 'S'

    AttributeName: 'date'
    AttributeType: 'S'
    KeySchema:

    AttributeName: 'id'
    KeyType: 'HASH'

    AttributeName: 'date'
    KeyType: 'RANGE'
    ProvisionedThroughput:
    ReadCapacityUnits: '5'
    WriteCapacityUnits: '5'

Here is what the properties represent:

  1. Resources: This is where you declare AWS resources.
  2. MyDynamoDBTable: This is a logical name for your DynamoDB table inside this template.
  3. Type: This is the type of resource you're creating. For a DynamoDB table, use AWS::DynamoDB::Table.
  4. Properties: These are the properties of the resource.
  5. TableName: This is the name of the table. Replace 'MyTable' with the name you want to give to your table.
  6. AttributeDefinitions: This is where you define all attributes for the table.
  7. AttributeName and AttributeType: These are the name and the type of the attribute. In this example, the attributes named 'id' and ‘date’ are both type 'S' (string).
  8. KeySchema: This is where you define the primary key of the table. You specify an attribute to act as the primary key of the table. In this example, 'id' is the primary key (or ‘hash’ key) and ‘date’ is the sort key (or ‘range’ key).
  9. ProvisionedThroughput: This is where you set the read and write capacity units for the table. This example creates a basic DynamoDB table with provisioned throughput. Depending on your use case, you might want to specify additional properties such as secondary indexes, stream specifications, Time to Live (TTL) attributes, etc.

Deploying the template

You can use AWS Management Console, the AWS CLI, or AWS SDKs to deploy a CloudFormation template. The following command could be used to deploy the above example, after it had been saved locally as dynamodb-table.yml, using the AWS CLI.

aws cloudformation create-stack --stack-name my-stack-name --template-body file://dynamodb-table.yml

Created by: