如何通过AWS CLI使用NoSQL Workbench导出的架构本地创建DynamoDB表?
我在NoSQL Workbench中创建了一张表,该工具支持将表导出为Workbench JSON或CloudFormation JSON格式。我希望借助其中一种格式,通过AWS CLI创建该表。
需求背景:我需要在Docker容器中创建数据库并运行测试,测试完成后删除表,每次测试都要重新创建全新的表,因此需要一种便捷的建表方式。
我尝试使用CloudFormation格式的表JSON文件,执行的创建命令如下:
DYNAMODB_ENDPOINT='http://localhost:8001' aws dynamodb create-table --cli-input-json file://table.json --endpoint-url $DYNAMODB_ENDPOINT
但执行命令时出现了一系列错误:
Missing required parameter in input: "AttributeDefinitions"
Missing required parameter in input: "TableName"
Missing required parameter in input: "KeySchema"
Unknown parameter in input: "AWSTemplateFormatVersion", must be one of: AttributeDefinitions, TableName, KeySchema, LocalSecondaryIndexes, GlobalSecondaryIndexes, BillingMode, ProvisionedThroughput, StreamSpecification, SSESpecification, Tags, TableClass
Unknown parameter in input: "Resources", must be one of: AttributeDefinitions, TableName, KeySchema, LocalSecondaryIndexes, GlobalSecondaryIndexes, BillingMode, ProvisionedThroughput, StreamSpecification, SSESpecification, Tags, TableClass
请问如何解决这个问题,实现通过AWS CLI本地创建该表?
问题核心是你用了CloudFormation格式的JSON,但aws dynamodb create-table命令要求的是DynamoDB API标准参数格式的JSON,两者结构完全不兼容。以下是三种解决方法:
方法1:直接导出Workbench JSON格式
回到NoSQL Workbench,选择导出为「Workbench JSON」格式——这种格式是为DynamoDB API量身定制的,完全兼容create-table命令。导出后直接用你原来的命令执行即可,无需修改任何内容。
方法2:手动转换CloudFormation JSON为API格式
如果只有CloudFormation格式的文件,可提取其中的表定义参数:
- 打开你的CloudFormation JSON文件,找到
Resources节点下对应表的Properties字段,这里包含了AttributeDefinitions、KeySchema、TableName等create-table需要的核心参数。 - 将这些参数单独提取出来,组成一个新的JSON文件,示例结构如下:
{ "TableName": "你的表名", "AttributeDefinitions": [ { "AttributeName": "id", "AttributeType": "S" }, { "AttributeName": "category", "AttributeType": "S" } ], "KeySchema": [ { "AttributeName": "id", "KeyType": "HASH" }, { "AttributeName": "category", "KeyType": "RANGE" } ], "BillingMode": "PAY_PER_REQUEST", "GlobalSecondaryIndexes": [ // 按需保留你的索引配置 ] }
- 用这个新JSON文件执行原
create-table命令即可。
方法3:用CloudFormation CLI部署(可选)
如果想保留CloudFormation格式,也可以用CloudFormation CLI直接部署本地DynamoDB表:
# 创建栈(即创建表) aws cloudformation deploy --template-file table.json --stack-name test-dynamodb-stack --endpoint-url http://localhost:8001 # 测试完成后删除栈(即删除表) aws cloudformation delete-stack --stack-name test-dynamodb-stack --endpoint-url http://localhost:8001
内容的提问来源于stack exchange,提问作者Pedro Henrique Bufulin

