属性定义不一致。

74

我有以下模板,我正在云编程UI中使用它来创建DynamoDB表。我想创建一个以ID为主键和Value为排序键的表。

{
  "AWSTemplateFormatVersion" : "2010-09-09",

  "Description" : "DB Description",

  "Resources" : {
    "TableName" : {
      "Type" : "AWS::DynamoDB::Table",
      "Properties" : {
        "AttributeDefinitions": [ { 
          "AttributeName" : "ID",
          "AttributeType" : "S"
        }, { 
          "AttributeName" : "Value",
          "AttributeType" : "S"
        } ],
        "KeySchema": [
          { 
            "AttributeName": "ID", 
            "KeyType": "HASH"
          }
        ]                
      },
      "TableName": "TableName"
    }
  }
}

在CF UI上,我点击新建堆栈,指向来自本地计算机的template文件,为堆栈命名并点击下一步。过一段时间后,我收到一个错误,错误信息是属性AttributeDefinitions与表和二级索引的KeySchema不一致


CloudFormation Linter规则可帮助更快地捕获此类问题,并提供更多信息:https://github.com/aws-cloudformation/cfn-python-lint/pull/1284 - Pat Myron
3个回答

126
问题在于Resources.Properties.AttributeDefinitions键必须定义用于索引或键的列。换句话说,Resources.Properties.AttributeDefinitions中的键必须与Resources.Properties.KeySchema中定义的相同键匹配。
AWS文档:

AttributeDefinitions:描述表格和索引的键模式的AttributeName和AttributeType对象列表。

所以最终的模板应该是这样的:
{
  "AWSTemplateFormatVersion" : "2010-09-09",

  "Description" : "DB Description",

  "Resources" : {
    "TableName" : {
    "Type" : "AWS::DynamoDB::Table",
    "Properties" : {
      "AttributeDefinitions": [ { 
        "AttributeName" : "ID",
        "AttributeType" : "S"
      } ],
      "ProvisionedThroughput":{
        "ReadCapacityUnits" : 1,
        "WriteCapacityUnits" : 1
      },
      "KeySchema": [
        { 
          "AttributeName": "ID", 
          "KeyType": "HASH"
        }
       ] ,               
      "TableName": "table5"
    }
   }
  }
}

3
如果我们从AttributeDefinitions中删除'value'属性,那么如何向表中添加“Value”列? - Dilantha
28
经过调研,创建 DynamoDB 表时不需要定义所有列,只需定义索引即可。然后,在插入新行时,可以动态地添加属性。 - ThomasP1988
https://dev59.com/lFYN5IYBdhLWcg3wdoAY 另一个解释 - ThomasP1988
问题说明了Value应该是排序键,因此它应该包含在KeySchema中,而不是从AttributeDefinitions中删除。 - Jason Wadsworth

1

接受的答案在错误原因方面是正确的,但是您说您希望排序键为Value。因此,您应该更改CloudFormation以包括它:

{
  "AWSTemplateFormatVersion" : "2010-09-09",

  "Description" : "DB Description",

  "Resources" : {
    "TableName" : {
      "Type" : "AWS::DynamoDB::Table",
      "Properties" : {
        "AttributeDefinitions": [ { 
          "AttributeName" : "ID",
          "AttributeType" : "S"
        }, { 
          "AttributeName" : "Value",
          "AttributeType" : "S"
        } ],
        "KeySchema": [
          { 
            "AttributeName": "ID", 
            "KeyType": "HASH"
          },
          { 
            "AttributeName": "Value", 
            "KeyType": "RANGE"
          }
        ]                
      },
      "TableName": "TableName"
    }
  }
}

0
在AttributeDefinitions中,您只需要定义分区键和排序键,而不是其他属性。
AttributeDefinitions和KeySchema中的属性数量应该匹配,并且应该完全相同。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接