1

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.

fedonev
  • 20,327
  • 2
  • 25
  • 34
  • Do you mind sharing what is your goal for trying to do this? – Allan Chua Jan 21 '22 at 03:41
  • To clarify, you are just updating the item in the table, not the table definition, am I correct? And what have you tried and what challenges you faced? Please update this information in the question. Normally you should be able to do so using mostly the same way you can update a table in the same stack. – Register Sole Jan 21 '22 at 05:50
  • Correct, I want to add or update item in the table but the table require to access from different stacks such as a stack handling input request needs to add item in the table as pending status and another stack which gets response back needs to update the item. basically I want to keep DynamoDB table stack separate which can be access by other stacks those are handling other functions. Hope this clarifies above both questions. Thanks for your response! – Uttam Malhotra Jan 21 '22 at 11:55

1 Answers1

3

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);
fedonev
  • 20,327
  • 2
  • 25
  • 34