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?
CodePudding user response:
ManagedPolicy.fromAwsManagedPolicyName("service-role/AmazonRedshiftDataFullAccess")
is trying to import the existing policy in your account. In your case, It is not created yet. You can create the managed policy in a different stack and add it as dependency to the stack which is creating the lambda fn. It ensures policy is created before lambda.
CodePudding user response:
okay I have made a couple of mistakes,
- It is
AmazonRedshiftDataFullAccess
, notservice-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"));
CodePudding user response:
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"));