amazon-web-servicesamazon-dynamodbaws-cloudformationserverlessserverless-framework

Cloudformation error when trying to create a DynamoDB table


I'm struggling to create a DynamoDB table through Cloudformation. I'm using the Serverless Framework as a layer on top of it, but the resource is written with Cloudformation Yaml notation, so it should work just as specified in their docs. This is the part of my serverless.yml to declare the DynamoDB resource:

resources:
    Resources:
        usersTable:
            Type: AWS::DynamoDB::Table
            Properties:
                TableName: users
                AttributeDefinitions:
                    - 
                      AttributeName: "id"
                      AttributeType: "S"
                    - 
                      AttributeName: "event_id"
                      AttributeType: "N"
                    - 
                      AttributeName: "date_created"
                      AttributeType: "N"
                    - 
                      AttributeName: "date_last_check"
                      AttributeType: "N"
                    - 
                      AttributeName: "can_pass"
                      AttributeType: "N"
                    - 
                      AttributeName: "counter_when_queued"
                      AttributeType: "N"
                KeySchema:
                    - 
                      AttributeName: "id"
                      KeyType: "HASH"
                    - 
                      AttributeName: "event_id"
                      KeyType: "RANGE"
                BillingMode: PAY_PER_REQUEST

but I'm getting this error when I try to deploy:

UPDATE_FAILED: usersTable (AWS::DynamoDB::Table)
Resource handler returned message: "Number of attributes in KeySchema does not exactly match number of attributes defined in AttributeDefinitions" (RequestToken: *********, HandlerErrorCode: InvalidRequest)

which is confusing because I can't define all the attributes in KeySchema (only 1 or 2 are allowed). Moreover, I'm following the same syntax as in examples like this: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-dynamodb.html

Any suggestion on how to fix this?


Solution

  • In DynamoDB you only define the attributes that you use as keys. Remove the non-key attributes that you've stored there and it'll work.

          AttributeDefinitions:
                        - 
                          AttributeName: "id"
                          AttributeType: "S"
                        - 
                          AttributeName: "event_id"
                          AttributeType: "N"
                    KeySchema:
                        - 
                          AttributeName: "id"
                          KeyType: "HASH"
                        - 
                          AttributeName: "event_id"
                          KeyType: "RANGE