HAPPY HACKING Oouchi's BLOG

PSE(ポンコツエンジニア)の技術ブログ

【DynamoDB エラー】Number of attributes in KeySchema does not exactly match number of attributes defined in AttributeDefinitions

f:id:ooooouchi:20200525090222p:plain

はじめに

初めてCloudFormationを使用してDynamoDBのテーブルを作成したときのエラーです。

本題

最初に作成した定義ファイル

AWSTemplateFormatVersion: 2010-09-09
Description: DynamoDb.
Parameters:
  Env:
    Type: String
    AllowedValues:
      - prod
      - stg
      - dev
Resources:
  SampleTable:
    Type: "AWS::DynamoDB::Table"
    Properties:
      TableName: SampleTable
      AttributeDefinitions:
        - AttributeName: sample_att_1
          AttributeType: S
        - AttributeName: sample_att_2
          AttributeType: S
        - AttributeName: sample_att_3
          AttributeType: S
      KeySchema:
        - AttributeName: sample_att_1
          KeyType: HASH
        - AttributeName: sample_att_2
          KeyType: RANGE
      BillingMode: PAY_PER_REQUEST
      Tags:
        - Key: Name
          Value: !Join ["-", [!Ref Env, SampleTable]]

CloudFormationでスタックを作成しようとしたところ以下のエラーが・・・

Number of attributes in KeySchema does not exactly match number of attributes defined in AttributeDefinitions

エラー内容

英語読めないのでGoogle翻訳で翻訳しました!

  • KeySchemaの属性の数が、AttributeDefinitionsで定義された属性の数と正確に一致していません

KeySchemaとAttributeDefinitionsの数は同じじゃないといけないらしいです。

DynamoDBの仕様上、Attributeは項目を追加するときに自由に増減できるのでKeySchemaに関わらない部分は定義しない方が幅広い使い方ができるよってことなんでしょうか。

ともかく、KeySchemaとAttributeDefinitionsの数を同じにして再度定義ファイルを作成します。

修正した定義ファイル

AWSTemplateFormatVersion: 2010-09-09
Description: DynamoDb.
Parameters:
  Env:
    Type: String
    AllowedValues:
      - prod
      - stg
      - dev
Resources:
  SampleTable:
    Type: "AWS::DynamoDB::Table"
    Properties:
      TableName: SampleTable
      AttributeDefinitions:
        - AttributeName: sample_att_1
          AttributeType: S
        - AttributeName: sample_att_2
          AttributeType: S
      KeySchema:
        - AttributeName: sample_att_1
          KeyType: HASH
        - AttributeName: sample_att_2
          KeyType: RANGE
      BillingMode: PAY_PER_REQUEST
      Tags:
        - Key: Name
          Value: !Join ["-", [!Ref Env, SampleTable]]

これで良さそうです☺

めでたし。

おわりに

こういったエラーはサービスの思想を深く理解していればそもそも発生しない気もしますね:( 使い方だけではなくそういったところも理解していきたいと思います!