amazon-web-servicesaws-lambdaaws-cdk

Cannot add ManagedPolicy to the lambda that is created in the same stack


I'm new to AWS CDK and I'm trying to set up lambda with few AWS managed policies.

Lambda configuration,

this.lambdaFunction = new Function(this, 'LambdaName', {
      functionName: 'LambdaName',
      description: `Timestamp: ${new Date().toISOString()} `,
      code: ...,
      handler: '...',
      memorySize: 512,
      timeout: Duration.seconds(30),
      vpc: ...,
      runtime: Runtime.PYTHON_3_8,
    });

I want to add AmazonRedshiftDataFullAccess ManagedPolicy to lambda role but couldn't find out a way to do it as addToRolePolicy supports only the PolicyStatement and not ManagedPolicy.

Tried something as following, it errored out saying role may be undefined.

this.lambdaFunction.role
        .addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName("service-role/AmazonRedshiftDataFullAccess"));

Could anyone help me understand what is the right way to add a ManagedPolicy to the default role that gets created with the lambda function?


Solution

  • okay I have made a couple of mistakes,

    The following worked for me,

    this.lambdaFunction.role
            ?.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName("AmazonRedshiftDataFullAccess"));