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
).