Update DynamoDB table from another stack in AWS CDK

I'm looking for a TypeScript code to update DynamoDB created in one stack from another stack by using lambda and API gateway. Both stacks are in the same environment. Please advice, if this is doable.


My understanding of your requirement: you previously deployed a CDK App with a DynamoDB table (let's call the App's Stack DynamoStack). Now you have a new stack - say, APIStack - with an API Gateway backed by a Lambda target. How does your APIStack get access to the table from DynamoStack so your Lambda can read/write to the table?

Prefer a Multi-Stack App

Ideally, you would add APIStack to the App that has your DynamoStack. It's generally good to group related stacks in a single CDK App. If you do so, it's trivial to pass resources between stacks. Just export the dynamodb.Table as a class field from DynamoStack and pass it to to APIStack as a prop.

Separate Apps

If for some reason grouping the Stacks in a single App is not feasible, wiring up cross-stack references takes a few more steps.

In DynamoStack, create a CloudFormation output, whose Export Name can be imported into the other stacks:

// DynamoStack.ts
new cdk.CfnOutput(this, 'TableArn', { value: table.tableArn, exportName: 'DemoTableArn' });

In APIStack, make a ITable reference using the imported ARN. Use it to set the Lambda env var and give the lambda read-write access to the table:

// ApiStack.ts
const tableArn = cdk.Fn.importValue('DemoTableArn');
const table: dynamodb.ITable = dynamodb.Table.fromTableArn(this, 'ITable', tableArn);

const func = new nodejs.NodejsFunction(this, 'MyHandlerFunction', {
  entry: path.join(__dirname, 'func.ts'),
  environment: {
    TABLE_NAME: cdk.Arn.extractResourceName(tableArn, 'table'),
  },
});

table.grantReadWriteData(func);