DynamoDB

Add DynamoDB table to stack

We’ll start with the AWS DynamoDB table.

  1. Add an import statement at the beginning of sls_app/sls_app_stack.py.
  2. Create an aws_dynamodb.Table counter
    • Table Name: counter
    • Partition Key: path (AttributeType.STRING)
from aws_cdk import (
    core,
    aws_dynamodb
)


class SlsAppStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        ## 1. Define the table that maps short codes to URLs.
        table = aws_dynamodb.Table(
            self, 
            "counter",
            partition_key={
                'name': 'path',
                'type': aws_dynamodb.AttributeType.STRING
            }
        )

A word about constructs and constructors

As you can see, the class constructors of both SlsAppStack and aws_dynamodb.Table (and many other classes in the CDK) have the signature (scope, id, **kwargs). This is because all of these classes are constructs. Constructs are the basic building block of CDK apps. They represent abstract “cloud components” which can be composed together into higher level abstractions via scopes. Scopes can include constructs, which in turn can include other constructs, etc.

Constructs are always created in the scope of another construct and must always have an identifier which must be unique within the scope it’s created. Therefore, construct initializers (constructors) will always have the following signature.

  1. scope: the first argument is always the scope in which this construct is created. In almost all cases, you’ll be defining constructs within the scope of current construct, which means you’ll usually just want to pass self for the first argument. Make a habit out of it.
  2. id: the second argument is the local identity of the construct. It’s an ID that has to be unique amongst construct within the same scope. The CDK uses this identity to calculate the CloudFormation Logical ID for each resource defined within this scope.
  3. kwargs: the last (sometimes optional) arguments is always a set of initialization arguments. Those are specific to each construct. For example, the aws_lambda.Function construct accepts arguments like runtime, code and handler.

CDK diff

Save your code, and let’s take a quick look at the cdk diff before we deploy:

cdk diff sls-app

CDK deploy

Let’s deploy

cdk deploy sls-app