AWS CDK 使用现有 DynamoDB 和流

mon*_*key 8 amazon-web-services amazon-dynamodb aws-cdk

我正在将我的云解决方案迁移到 cdk。我可以看到如何通过 TableProps 在构造函数中将流添加到新的 DynamoDB:

const newTable = new dynamodb.Table(this, 'new Table', {
  tableName: 'streaming',
  partitionKey: { name : 'id', type: dynamodb.AttributeType.NUMBER },
  stream: StreamViewType.NEW_AND_OLD_IMAGES,
})
Run Code Online (Sandbox Code Playgroud)

但没有明显的方法可以在现有 DynamoDB 上启用流。我似乎无法访问现有项目上的 TableProps。

const sandpitTable = dynamodb.Table.fromTableArn(this, 'sandpitTable', 'arn:aws:dynamodb:ap-southeast-2:xxxxxxxxxxxxxx:table/Sandpit');
sandpitTable.grantStreamRead(streamLambda);
// sandpitTable.  ??? what to do?
Run Code Online (Sandbox Code Playgroud)

如何才能实现这一目标?该解决方案如何考虑灾难恢复并防止使用控制台时不可能发生的 Dynamo DB 意外删除。

Bal*_*ala 5

启用流只是 CloudFormation 中资源“AWS::DynamoDB::Table”的另一个属性,我不相信我们可以更改从另一个 cloudformation/cdk 堆栈在堆栈中(或手动)创建的资源,除非我们导入资源。 是文档。我可以尝试总结一下。

  • 假设我们有一个现有的 cdk 项目,该项目部署时没有元数据资源cdk --no-version-reporting deploy

  • 假设我们有 Dynamo 表“流”,分区键为“id”,如您所述。

  • 添加下面的 cdk 代码,其属性与原始表相同,如 RCU、WCU、密钥等。为简单起见,我只给出了名称和密钥,removePolicy 是必须的

    const myTable = new dynamodb.Table(this, "dynamo-table", {
      tableName: "streaming",
       partitionKey: { name: "id", type: dynamodb.AttributeType.NUMBER },
       removalPolicy: cdk.RemovalPolicy.RETAIN,
    });
    
    Run Code Online (Sandbox Code Playgroud)
  • 我们现在可以合成并默认生成 CloudFormation 到 cdk.out 文件夹中cdk --no-version-reporting synth

  • 从 .json 文件中获取逻辑 ID,在我的例子中它是 dynamotableF6720B98

  • 使用正确的表名称和逻辑 ID 创建变更集集 aws cloudformation create-change-set --stack-name HelloCdkStack --change-set-name ImportChangeSet --change-set-type IMPORT --resources-to-import "[{\"ResourceType\":\"AWS::DynamoDB::Table\",\"LogicalResourceId\":\"dynamotableF6720B98\",\"ResourceIdentifier\":{\"TableName\":\"streaming\"}}]" --template-body file://cdk.out/HelloCdkStack.template.json

  • 执行变更集

    aws cloudformation execute-change-set --change-set-name ImportChangeSet --stack-name HelloCdkStack

  • 最好检查漂移并进行必要的更改 aws cloudformation detect-stack-drift --stack-name HelloCdkStack

对于防止意外删除的另一个问题,我们可以简单地添加删除策略,以避免在删除堆栈/资源时删除发电机表。

removalPolicy: RemovalPolicy.RETAIN
Run Code Online (Sandbox Code Playgroud)

  • 这不再是真的——Cloud Formation 支持导入某些类型资源的现有资源,包括现有 DynamoDB 表:https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-import.html (2认同)