简体   繁体   中英

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 eg 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM