Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Lambda trigger to imported Cognito User Pool with AWS CDK

I'm trying to use AWS CDK to create a new lambda tied to already existing AWS resources which were not created using CDK and that are part of a different stack.

Can I trigger my lambda from an already existing user pool using CDK? I've imported the user pool to my new stack using:

const userPool = UserPool.fromUserPoolArn(this, 'poolName, 'arn:aws:cognito-idp:eu-west-1:1234567890:userpool/poolName')

However, this gives me an IUserPool which does not have the addTrigger method. Is there a way to convert this into a UserPool in order to be able to trigger the lambda (since I can see that UserPool has the addTrigger method)?

I have seen that it is possible to e.g. grant permissions for my new lambda to read/write into an existing DynamoDB table using CDK. And I don't really understand the difference here: DynamoDB is an existing AWS resource and I'm importing it to the new stack using CDK and then allowing my new lambda to modify it. The Cognito User Pool is also an existing AWS resource, and I am able to import it in CDK but it seems that I'm not able to modify it? Why?

like image 451
greenTea Avatar asked May 15 '20 09:05

greenTea


Video Answer


1 Answers

This was discussed in this issue. You can add triggers to an existing User Pool using a Custom Resource:

import * as CustomResources from '@aws-cdk/custom-resources';
import * as Cognito from '@aws-cdk/aws-cognito';
import * as Iam from '@aws-cdk/aws-iam';

const userPool = Cognito.UserPool.fromUserPoolId(this, "UserPool", userPoolId);

new CustomResources.AwsCustomResource(this, "UpdateUserPool", {
      resourceType: "Custom::UpdateUserPool",
      onCreate: {
        region: this.region,
        service: "CognitoIdentityServiceProvider",
        action: "updateUserPool",
        parameters: {
          UserPoolId: userPool.userPoolId,
          LambdaConfig: {
            PreSignUp: preSignUpHandler.functionArn
          },
        },
        physicalResourceId: CustomResources.PhysicalResourceId.of(userPool.userPoolId),
      },
      policy: CustomResources.AwsCustomResourcePolicy.fromSdkCalls({ resources: CustomResources.AwsCustomResourcePolicy.ANY_RESOURCE }),
    });

const invokeCognitoTriggerPermission = {
        principal: new Iam.ServicePrincipal('cognito-idp.amazonaws.com'),
        sourceArn: userPool.userPoolArn
}

preSignUpHandler.addPermission('InvokePreSignUpHandlerPermission', invokeCognitoTriggerPermission)

You can also modify other User Pool settings with this method.

like image 82
AndyDeveloper Avatar answered Sep 27 '22 21:09

AndyDeveloper