1. How to attach IAM policy to Lambda for DynamoDB access?

    TypeScript

    To achieve this, you will use two main resources, aws.iam.Policy and aws.lambda.Function.

    First, you will create an IAM policy that allows the necessary DynamoDB actions. It's recommended to follow the principle of least privilege, and only grant the permissions that are absolutely necessary for your function.

    Next, you will create a Lambda function. For the role property of the Lambda function, which represents the IAM role used by the Lambda function, you will attach the previously created IAM policy.

    Below is the code:

    import * as pulumi from "@pulumi/pulumi"; import * as aws from "@pulumi/aws"; // Create IAM Policy for DynamoDB const dynamoDbPolicy = new aws.iam.Policy("dynamoDbPolicy", { policy: pulumi.interpolate`{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "dynamodb:GetItem", "dynamodb:Scan", "dynamodb:Query", "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:DeleteItem" ], "Resource": "arn:aws:dynamodb:us-west-2:123456789012:table/my-table" } ] }` }); // Create an IAM role and attach the policy const role = new aws.iam.Role("lambdaRole", { assumeRolePolicy: `{ "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Principal": { "Service": "lambda.amazonaws.com" }, "Effect": "Allow", "Sid": "" } ] }` }); new aws.iam.RolePolicyAttachment("lambdaDynamoDbAttachment", { role: role, policyArn: dynamoDbPolicy.arn }); // create a Lambda function, using the IAM role and policy const lambda = new aws.lambda.Function("mylambda", { code: new pulumi.asset.FileArchive("lambda-handler.zip"), handler: "index.handler", role: role.arn, runtime: aws.lambda.NodeJS14dXRuntime, });

    This code does the following:

    • aws.iam.Policy creates an IAM Policy that allows access to the specified DynamoDB actions on the specified table.
    • aws.iam.Role creates a new IAM role that the Lambda function will assume.
    • aws.iam.RolePolicyAttachment connects our previously created IAM Policy with the IAM Role.
    • aws.lambda.Function uses the attached policy to access DynamoDB from within the Lambda function.

    Note: Remember to replace "arn:aws:dynamodb:us-west-2:123456789012:table/my-table" with the ARN of your DynamoDB table.

    The value "lambda-handler.zip" represents the zip file containing your Lambda function code. You'll need to replace this with the path to your own zip file.

    The index.handler value represents the entry point into your Lambda function, in this case a file named index.js with an exported function named handler. Adjust this according to your own Lambda function's entry point.

    aws.iam.Policy

    aws.lambda.Function

    aws.iam.Role

    aws.iam.RolePolicyAttachment