Specifying a custom role for lambda with the AWS CDK

The accepted answer by @rix0rrr doesn't work any more. Seems CDK get some updates. Currently version is

"@aws-cdk/core": "^1.1.0"

Updated code:

    import iam = require("@aws-cdk/aws-iam");

    const statement = new iam.PolicyStatement();
    statement.addActions("lambda:InvokeFunction");
    statement.addResources("*");

    lambda.addToRolePolicy(statement); 

A Lambda already comes with an execution role, and it already has the basic execution permissions. If you want to add additional permissions to the role it has, do something like the following:

import * as iam from '@aws-cdk/aws-iam';

lambda.addToRolePolicy(new iam.PolicyStatement()
   .addResource('arn:aws:....')
   .addAction('s3:GetThing'));

Or better yet, use one of the convenience functions for permissions on some resources:

bucket.grantRead(lambda.role);

Even though the lambda comes with an IAM role, you can create a custom role for the lambda. You just have to make sure to assign correct minimum required permissions to it.

You can create a role like this:

    const customRole = new Role(this, 'customRole', {
                    roleName: 'customRole',
                    assumedBy: new ServicePrincipal('lambda.amazonaws.com'),
                    managedPolicies: [
                        ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaVPCAccessExecutionRole"),
                        ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole")
                    ]
                })

If the lambda does not need to be in a VPC you can skip AWSLambdaVPCAccessExecutionRole.

And to assign this role to the lambda function:

const lambda = new lambda.Function(this, 'lambda', {
                runtime:....,
                code:...,
                role: customRole,
                handler:....,
                memorySize:...,
                timeout:....,
                vpc:...,
                environment: {
                   ....
                }
            });