Utilizing CDK to apply policies to roles using a loop through each item

I am attempting to create a Role with specific policies, which will vary depending on the lambda function. My goal is to have a function that can create both the role and policies when called with the desired role name and policies attached. This is what I have so far:

Example of creating a lambda role:

...
    const lambdarole = this.createLambdaRole( 'Test Role', [
      'KMSLambdaPolicy',
      'S3LambdaPolicy',
    ]);
...

Function for creating Role and policies:

  private createLambdaRole(roleName: string, policyName: string[]) {
    const role = new Role(this, 'Role', {
      roleName: roleName,
      assumedBy: new ServicePrincipal('lambda.amazonaws.com'),
      description: 'Role for lambda access',
      managedPolicies: [],
    });

    const kmspolicy = new ManagedPolicy(this, 'KMSLambdaPolicy', {
      managedPolicyName: 'KMSLambdaPolicy',
      statements: [
        new PolicyStatement({
          effect: Effect.ALLOW,
          actions: [
            'kms:Decrypt',
            'kms:GenerateDataKey',
            'kms:DescribeKey'],
        }),
      ],
    });

    const s3policy = new ManagedPolicy(this, 'S3LambdaPolicy', {
      managedPolicyName: 'S3LambdaPolicy',
      statements: [
        new PolicyStatement({
          effect: Effect.ALLOW,
          actions: [
            's3:PutObject',
            's3:GetObject',
            's3:GetObjectAttributes'],
          resources: ['*'],
        }),
      ],
    });

    policyName.forEach(policyName => role.addManagedPolicy(policyName));

    return role;
  }

I am encountering an error and unable to get it to work:

error TS2345: Argument of type 'string' is not assignable to parameter of type 'IManagedPolicy'.

Is it possible to achieve what I want?

Thank you to anyone who is willing to assist!

SOLUTION FOUND

I was able to resolve the issue with the following code:

policyName.forEach(policyName => {
  const importedPolicy = ManagedPolicy.fromManagedPolicyName(this, policyName, policyName);
  role.addManagedPolicy(importedPolicy);
});

Note: addManagedPolicy requires a scope, an id, and a policy name. Since my policy IDs and names are the same, I simply needed to call the array again (hence the this, policyName, policyName).

Answer №1

When using the addManagedPolicy function, it is important to provide an IManagedPolicy object instead of a string.

    // To ensure reusability, define your managed policy once for the entire account
    // and make sure it has a unique identifier.
    // Here's an example of creating a customer-managed policy.
    const kmspolicy = new ManagedPolicy(this, 'MP-KMSLambda', {
      managedPolicyName: 'KMSLambdaPolicy'
      // etc.
    }); 

    // You can attach the role anywhere in your CDK application,
    // such as in another construct or stack.
    //
    // The policyNames list should match the identifiers of your 
    // new ManagedPolicies.
    const policyNames = ['KMSLambdaPolicy'];
    policyNames.forEach(policyName => {
       const importedPolicy = iam.ManagedPolicy.fromManagedPolicyName(this, `${role.roleName}-${policyName}`, policyName)
       role.addManagedPolicy(importedPolicy)
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate matTooltip dynamically into text for targeted keywords

I'm currently tackling a challenge in my personal Angular project that utilizes Angular Material. I'm struggling to find a solution for the following issue: For instance, I have a lengthy text passage like this: When you take the Dodge action, ...

Ways to confirm if a user has previously participated in a poll?

SCENARIO: At present, I am storing an array of objects within the User model to track all the votes cast by the user. Here is a glimpse of the model structure: var schema = new Schema({ firstName: {type: String, required: true}, lastName: {type: ...

Using TypeScript to ensure class parameter types without affecting properties

I am tasked with defining a schema for "operations" that will be used in my application. This schema must be easily extendable for other groups of "operations" and should include a dictionary of settings for each keyword. Eventually, a "generic caller" wi ...

How can I loop through a JSON object in Angular 8 using a function?

Within my component.ts file, I have developed a function: getData(id) { const idMod = id const idModN = document.getElementById("idMod").innerHTML = idMod console.log (idModN) } My goal is to click on a button and have the id of each ...

Issue with Angular 4: Mega menu does not automatically close when a menu item is selected from within it

I am currently working on an Angular 4 project that includes a mega menu. My issue is that when I click on a menu within the mega menu, I want it to close. However, in my current setup, the menu always remains open even after clicking on a specific option. ...

Tips for creating a typescript module definition that exports a module dependency as one of its members

Let's consider a particular situation: I am in the process of creating typescript definitions for two commonJS modules, A and B. Module B has a dependency on module A, and to make things easier, B directly exports A as a property B.A so that users do ...

Incorporating TypeScript seamlessly into your current Create React App project without the need to modify any existing code or files

While I have already installed Typescript in my project, I am more concerned about adding new .tsx files and ensuring they are type-checked. Simply renaming existing .js files to .tsx is not a viable solution, as it requires refactoring all the existing ...

Changing the fill color of externally imported SVGs from a CDN: A simple guide

While working on a website project using Next JS, I came across the challenge of displaying SVG icons stored in Sanity and dynamically changing their fill color. Is it possible to achieve this feature, such as changing the color when hovering over the icon ...

Having trouble deciding between flatMap and concatMap in rxJs?

Having trouble grasping the distinction between flatMap and concatMap in rxJs. The most enlightening explanation I found was on this Stack Overflow post about the difference between concatMap and flatMap So, I decided to experiment with it myself. import ...

Unlock Buffer - JavaScript

I'm working with a simple JavaScript code snippet. let str = "Hello World"; console.log(Buffer.from(str,"utf-8")); The output is: <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64> Is there a way to extract the bytes from the Buffe ...

What is the process for invoking an asynchronous cleanup function?

Is it possible to trigger an async cleanup function within useEffect? useEffect(() => { return () => Voice.destroy().then(Voice.removeAllListeners); }, []); Keep in mind that the EffectCallback requires a return of void, not Promise<void> ...

Function that returns a lookup map for TypeScript enums

For my React project, I've created a function that transforms a lookup class into an array that can be used. The function is functioning properly, but it seems to loop through the enum twice, resulting in undefined values for the first iteration. Alt ...

Adjust website content depending on user's authentication status

My goal is to display a logout button when the user is logged in and a login button if they are not. I am using JSON tokens to determine if a user is logged in or not, by checking if the token is null. However, this approach does not seem to be working. Ca ...

Encountering unexpected errors with Typescript while trying to implement a simple @click event in Nuxt 3 projects

Encountering an error when utilizing @click in Nuxt3 with Typescript Issue: Type '($event: any) => void' is not compatible with type 'MouseEvent'.ts(2322) __VLS_types.ts(107, 56): The expected type is specified in the property ' ...

I prefer the value to switch to false whenever I navigate to a new route and then return to the previous route, as the sidebar remains open

click here for image details view image description here Struggling to set the value as false when revisiting this site. Need assistance! Could someone lend a hand, please? ...

Error! Unable to Inject ComponentFactoryResolver

Recently, I attempted to utilize ComponentFactoryResolver in order to generate dynamic Angular components. Below is the code snippet where I am injecting ComponentFactoryResolver. import { Component, ComponentFactoryResolver, OnInit, ViewChild } from "@an ...

What is the proper way to utilize a service within a parent component?

I need assistance with setting up inheritance between Child and Parent components. I am looking to utilize a service in the Parent component, but I have encountered an issue. When attempting to input the service in the Parent constructor like this: expor ...

Is there a way to customize the hover style of Material UI Select or Menu MenuItem using the theme?

The theme I designed import { createMuiTheme } from 'material-ui/styles'; export const MyTheme = createMuiTheme({ palette: { primary: { light: '#757ce8', main: '#3f50 ...

Generating objects dynamically using Angular 2 framework

My goal is to dynamically create objects and add data using TypeScript. For instance: let data={ "date":"27-5-2017", "name":"John" }; This represents my initial object. Now, I aim to include additional data in it, such as subjects. "Subject1":" ...

I am attempting to store the primary array in local storage, but unfortunately, the value is not being saved within the React context API

I attempted to store the main array in local storage and retrieve it as global state, but I am facing an issue where the data is not being saved in the local storage. This file represents my context. import { createContext, useReducer, ReactNode, FC, use ...