I am fairly new to AWS CDK and haven't had a lot of experience with AWS. In my CDK stack that I am writing, I have to give permissions to resources that are built with other CDK templates and are already in aws.
Lets say, my stack A contains a lambda, the lambda will be invoked from another service X. The service X needs to have invoke permission of lambda. Can I give the service X permission from the Stack A code or will I need to modify the service X stack?
In general, the answer is yes, you can add permissions to resources created outside the stack. But, You need to make sure the resource is importable.
Lambda usage:
add a policy to lambda role:
More info here.
const importedLambda = lambda.Function.fromFunctionArn(scope,`${name}-lambda`,${LAMBDA_ARN});
importedLambda.addToRolePolicy(new iam.PolicyStatement({
effect: iam.Effect.ALLOW, // ... and so on defining the policy
}));
add permission to lambda:
More info here.
const importedLambda = lambda.Function.fromFunctionArn(scope,`${name}-lambda`,${LAMBDA_ARN});
importedLambda.addPermission('allowInvocation',{
principal: new ServicePrincipal('events.amazonaws.com'), // ... and so on defining the permission
sourceArn: ...
});
You don't have to modify service X Stack.
The examples below assume you are using typescript.
If you want to allow the whole service (not recommended) invoke permission on your lambda you can use following:
For S3
yourfunction.grantInvoke(new ServicePrincipal('s3.amazonaws.com'));
For SNS
yourfunction.grantInvoke(new ServicePrincipal('sns.amazonaws.com'));
But I would recommend specifying the specific resource ARN that you want to allow to invoke your lambda. For example if its another lambda function you can specify its Role ARN like following:
yourfunction.grantInvoke(new ArnPrincipal('arn:aws:iam:region:account-id:role/role-name'));
And as Amit mentioned in his answer you can also use addPermission if you want to specify more granular permissions. You can use addPermission to even allow resources in other AWS accounts to invoke your lambda.
You can use "cdk bootstrap" to track the aws key permission can meet the cdk requirement.
cdk bootstrap
⏳ Bootstrapping environment aws://999999999999/us-west-2...
✅ Environment aws://999999999999/us-west-2 bootstrapped (no changes).
Above is fine prinout.
I read the guide from https://cdkworkshop.com/20-typescript/20-create-project/500-deploy.html