I am new to AWS CDK and have run into an issue wwhen setting up my Lambda. Here is my code:
import { ManagedPolicy, Role, Group, User } from 'aws-cdk-lib/aws-iam';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { LambdaIntegration } from 'aws-cdk-lib/aws-apigateway';
const group1 = new Group(this, 'group-1', {
managedPolicies: [
ManagedPolicy.fromAwsManagedPolicyName('AdministratorAccess'),
ManagedPolicy.fromAwsManagedPolicyName('AmazonEC2FullAccess'),
ManagedPolicy.fromAwsManagedPolicyName('SecretsManagerReadWrite'),
ManagedPolicy.fromAwsManagedPolicyName('IAMFullAccess'),
ManagedPolicy.fromAwsManagedPolicyName('AmazonS3FullAccess'),
ManagedPolicy.fromAwsManagedPolicyName('AmazonAPIGatewayAdministrator'),
ManagedPolicy.fromAwsManagedPolicyName(
'AmazonEC2ContainerRegistryFullAccess'
),
ManagedPolicy.fromAwsManagedPolicyName('AmazonRDSFullAccess'),
ManagedPolicy.fromAwsManagedPolicyName('AmazonSSMFullAccess'),
ManagedPolicy.fromAwsManagedPolicyName('AmazonCognitoPowerUser')
]
});
const group2 = new Group(this, 'group-2', {
managedPolicies: [
ManagedPolicy.fromAwsManagedPolicyName('AWSCloudFormationFullAccess'),
ManagedPolicy.fromAwsManagedPolicyName('AWSLambda_FullAccess')
]
});
const user = new User(this, 'root', {});
group1.addUser(user);
group2.addUser(user);
const lambdaRole = new Role(this, 'lambdaRole', {
roleName: 'lambdaRole',
assumedBy: user
});
const lambda = new LambdaIntegration(
new NodejsFunction(this, 'statusFunction', {
entry: 'lambda.js',
functionName: 'lambda',
role: lambdaRole,
})
);
I have created some groups that contain a range of policies and I have attached a user to those two groups. I want to now use that user with all these permissions to execute a lambda function. My understanding is that in order to be able to do so I have to first create a role for the lambda which I have done. I then configure the assumedBy prop of the new role to be the user I just created with all the permissions - my understanding is that this should pass down all the permissions of the user to the role that will execute the lambda...
When I try deploy (via cdk deploy) I get the following error:
the role defined for the function cannot be assumed by lambda
Why would this be?
Your Lambda's role needs to be assumable by the Lambda service principal, not by the user.
You may find it easier to not create the Lambda directly and instead let the NodejsFunction construct create the Role for you. Add any permissions your Lambda function needs by calling the .addToRolePolicy function.
If you're trying to let your user invoke the function, then you need something like:
const lambdaFunction = new NodejsFunction(this, 'statusFunction', {
entry: 'lambda.js',
functionName: 'lambda',
role: lambdaRole,
});
const lambda = new LambdaIntegration(
lambdaFunction
);
group1.grantInvoke(lambdaFunction);