Provide an example of how to grant a NodejsFunction specific AWS IAM permissions to interact with other AWS services.

Responsive Ad Header

Question

Grade: Education Subject: Support
Provide an example of how to grant a NodejsFunction specific AWS IAM permissions to interact with other AWS services.
Asked by:
117 Viewed 117 Answers

Answer (117)

Best Answer
(919)
You can grant IAM permissions to a `NodejsFunction` by calling methods on its `grant` object or directly manipulating its `role`. The `grant` methods are generally preferred as they ensure least privilege. For example, to grant read access to an S3 bucket: ```typescript import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs'; import { Runtime } from 'aws-cdk-lib/aws-lambda'; import { Bucket } from 'aws-cdk-lib/aws-s3'; const myBucket = new Bucket(this, 'MyDataBucket', { /* ... */ }); const myFunction = new NodejsFunction(this, 'MyFunctionWithS3Access', { entry: 'src/lambda/handler.ts', runtime: Runtime.NODEJS_20_X, }); // Grant read permissions to the function on the S3 bucket myBucket.grantRead(myFunction); // Or, for more granular control: // myFunction.addToRolePolicy( // new PolicyStatement({ // actions: ['sqs:SendMessage'], // resources: [myQueue.queueArn], // }) // ); ```