skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    okay I have made a couple of mistakes,

    • It is AmazonRedshiftDataFullAccess, not service-role/AmazonRedshiftDataFullAccess
    • As the role is optional here, I should have done Optional Chaining (?.)

    The following worked for me,

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

  2. Its a 3 step process :-

    • You need to first create role for lambda.

    • create lambda and attach role to lambda.

    • add aws managed( make sure its correct name ) policy to lambda.

    example

        const myRole = new iam.Role(this, 'My Role', {
      assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
      });
    
      const fn = new lambda.Function(this, 'MyFunction', {
      runtime: lambda.Runtime.NODEJS_16_X,
      handler: 'index.handler',
      code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
      role: myRole, // user-provided role
      });
    
      myRole.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName("AmazonRedshiftDataFullAccess"));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search