aws-lambdaamazon-dynamodbamazon-iamaws-cdkaws-cdk-typescript

How do I grant access for a Lambda to read and or write to a DynamoDB table using CDK?


I am using AWS CDK to set up a simple CRUD webservice, where a set of lambdas will read and write to a DynamoDB table.

The suggestion from ChatGPT was to set up access like so:

// Create a DynamoDB table
const table = new dynamodb.Table(scope, utils.prefixed('stable-diffusion'), {
    partitionKey: { name: 'ID', type: dynamodb.AttributeType.STRING },
    // sortKey: { name: 'SK', type: dynamodb.AttributeType.STRING },
    billingMode: dynamodb.BillingMode.PAY_PER_REQUEST, // use pay-per-request billing mode
    removalPolicy: cdk.RemovalPolicy.DESTROY, // delete the table when the stack is deleted
    // timeToLiveAttribute: 'ttl', // enable TTL for items in the table
    tableName: utils.prefixed('stable-diffusion'), // optional: specify a custom table name
});

// Add an IAM policy to allow read and write access to the table
const policy = new iam.PolicyStatement({
    effect: iam.Effect.ALLOW,
    actions: ['dynamodb:GetItem', 'dynamodb:PutItem', 'dynamodb:DeleteItem'],
    resources: [table.tableArn],
});
table.grantReadWriteData(policy);

However this gives me the error: "Argument of type 'PolicyStatement' is not assignable to parameter of type IGrantable.

What is the correct way to achieve this?


Solution

  • I'm not on my laptop to double check this for you, but I usually do something like the following:

    // myTable definition
    // myLambda definiton
    
    myTable.grantReadWriteData(myLambda)