AWS CloudFormation - Create DynamoDB datrabase tables in your CloudFromation templates

Examples below include an auto delete if time is passed the UNIX seconds timestamp stored in the exp attribute, a number datatype.

Example with one key, a hash key named attr1.

Resources:
  Table:
    Type: AWS::DynamoDB::Table
    Properties:
      AttributeDefinitions:
        - AttributeName: "attr1"
          AttributeType: "S"
      BillingMode: "PAY_PER_REQUEST"
      KeySchema:
        - AttributeName: "attr1"
          KeyType: "HASH"
      TableName: "TABLE_NAME"
      TimeToLiveSpecification:
        AttributeName: "exp"
        Enabled: true

Example with two keys, a hash key named attr1 and a range key named attr2.

Resources:
  Table:
    Type: AWS::DynamoDB::Table
    Properties:
      AttributeDefinitions:
        - AttributeName: "attr1"
          AttributeType: S
        - AttributeName: "attr2"
          AttributeType: S
      BillingMode: "PAY_PER_REQUEST"
      KeySchema:
        - AttributeName: "attr1"
          KeyType: HASH
        - AttributeName: "attr2"
          KeyType: RANGE
      TableName: "TABLE_NAME"
      TimeToLiveSpecification:
        AttributeName: "exp"
        Enabled: true

Example with hash key and secondary global index

Resources:
  Table:
    Type: AWS::DynamoDB::Table
    Properties:
      AttributeDefinitions:
        - AttributeName: "attr1"
          AttributeType: S
        - AttributeName: "attr2"
          AttributeType: S
      BillingMode: "PAY_PER_REQUEST"
      GlobalSecondaryIndexes:
        - IndexName: "attr2Attr1"
          KeySchema:
            - AttributeName: "attr2"
              KeyType: HASH
            - AttributeName: "attr1"
              KeyType: RANGE
          Projection:
            NonKeyAttributes:
              - "attr3"
            ProjectionType: INCLUDE
      KeySchema:
        - AttributeName: "attr1"
          KeyType: HASH
      TableName: !Sub "${AWS::StackName}-table"

See Secondary indexes in the Amazon DynamoDB Developer Guide.

See AWS::DynamoDB::Table in the AWS CloudFormation User Guide.