Search code examples
c#amazon-web-servicesaws-cdkamazon-cognito-triggers

Assigning one lambda function to multiple Cognito User Pool triggers


In my CDK I create a lambda function lets call NotifyLambda that can be assigned to a Cognito User Pool CustomMessage trigger. For some reason if I apply this lambda function to one user pool, it works fine. But if I try to assign this lambda function to multiple user pools (which I can do in the AWS console) I get the below error:

Unhandled exception. Amazon.JSII.Runtime.JsiiException: There is already a Construct with name 'CustomMessageCognito' in Function [NotifyLambda ] at Amazon.JSII.Runtime.Services.Client.TryDeserialize[TResponse](String responseJson) at Amazon.JSII.Runtime.Services.Client.ReceiveResponseTResponse at Amazon.JSII.Runtime.Services.Client.Send[TRequest,TResponse](TRequest requestObject) at Amazon.JSII.Runtime.Services.Client.Create(CreateRequest request) at Amazon.JSII.Runtime.Services.Client.Create(String fullyQualifiedName, Object[]

Here is the sample code I use to build the user pools, its in a loop:

   var test = new Function(this, "Notifylambda", new Amazon.CDK.AWS.Lambda.FunctionProps
       {
           Runtime = Runtime.DOTNET_6,
           Code = Code.FromBucket(
                sourceBuildsBucket,
               "some zipped file"),
             Handler= "some handler"
       }  );

        //client list
        var clients = new List<int>() { 1,2,3,4};


    //loop through each one and try creating the user pool using the same custom message lambda
      
        foreach (var client in clients)
        {
           var UserPool = new UserPool(this,
           $"{client}UserPool",
           new UserPoolProps
           {
               UserPoolName = $"MyApp_{props.EnvironmentName}_{client}_UserPool", 
               LambdaTriggers = new UserPoolTriggers
               {
                   CustomMessage = test
               }
           });
         
        }

Where I pass in NotifyLambda as input for props.CustomMessageLambdaFunction.

Again, top code works fine for the first userpool I create but errors out on subsequence attempts to assign it to other user pools.


Solution

  • This is a bug in CDK that's caused by the fact that CDK is creating an IAM permission in the scope of the function with a static name, which causes a name collision.

    The source of the bug is in this line:

    https://github.com/aws/aws-cdk/blob/2ed006e50b15dfca96395d442ccee648abdbb374/packages/%40aws-cdk/aws-cognito/lib/user-pool.ts#L980

    UPDATE:

    This has been fixed in CDK 2.47.0 via https://github.com/aws/aws-cdk/pull/22444