问题
I'm migrating my cloud solution to cdk. I can see how to add a stream to a new DynamoDB in the constructor through the TableProps:
const newTable = new dynamodb.Table(this, 'new Table', {
tableName: 'streaming',
partitionKey: { name : 'id', type: dynamodb.AttributeType.NUMBER },
stream: StreamViewType.NEW_AND_OLD_IMAGES,
})
but there is no apparent way to enable a stream on an existing DynamoDB. I can't seem to access the TableProps on an existing item.
const sandpitTable = dynamodb.Table.fromTableArn(this, 'sandpitTable', 'arn:aws:dynamodb:ap-southeast-2:xxxxxxxxxxxxxx:table/Sandpit');
sandpitTable.grantStreamRead(streamLambda);
// sandpitTable. ??? what to do?
How can this be achieved? And how does the solution take into account disaster recovery and prevent accidental deletion of the Dynamo DB that is not possible when using the console.
回答1:
Enabling streams is just another attribute of resource 'AWS::DynamoDB::Table' in CloudFormation and I don't believe we can make changes to a resource that is created in a stack (or manually) from another cloudformation/cdk stack unless we import the resource. Here is documentation. I can try and summarize.
Assume we have an existing cdk project which is deployed without Metadata resource
cdk --no-version-reporting deploy
Assuming we have Dynamo table 'streaming' with partiion key 'id' as you stated.
Adding below cdk code with same attributes of original table like RCU, WCU, keys, etc. For simplicity I just gave name and key and removalPolicy is must
const myTable = new dynamodb.Table(this, "dynamo-table", { tableName: "streaming", partitionKey: { name: "id", type: dynamodb.AttributeType.NUMBER }, removalPolicy: cdk.RemovalPolicy.RETAIN, });
We can now synth and generate the CloudFormation by default into cdk.out folder
cdk --no-version-reporting synth
Grab the logical Id from .json file in my case it is dynamotableF6720B98
Create ChangeSet set with right table name and logical 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
Execute change set
aws cloudformation execute-change-set --change-set-name ImportChangeSet --stack-name HelloCdkStack
Best to check the drift and make necessary chagnes to
aws cloudformation detect-stack-drift --stack-name HelloCdkStack
To your other question of preventing accidental deletion, we can simply add deletion policy to avoid dynamo table getting deleted when stack/resource is deleted.
removalPolicy: RemovalPolicy.RETAIN
来源:https://stackoverflow.com/questions/65557316/aws-cdk-working-with-existing-dynamodb-and-streams