You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将单个Lambda函数分配至多个Cognito用户池触发时报错

解决AWS CDK中同一Lambda绑定多个Cognito用户池的命名冲突问题

问题原因

当你将同一个Lambda函数通过LambdaTriggers.CustomMessage绑定到多个用户池时,CDK会自动为每个绑定创建一个默认名为CustomMessageCognito的辅助Construct(用于管理Lambda的权限等关联资源)。循环中多次创建同名Construct会触发命名冲突,导致报错。

解决方案

不要在创建UserPool时直接设置触发器,而是先创建用户池,再通过AddCustomMessageTrigger方法手动绑定Lambda,并为每个绑定指定唯一的构造ID,避免名称重复。

修改后的代码示例

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};

//循环创建用户池并绑定触发器,使用唯一ID避免冲突
foreach (var client in clients)
{
   var userPool = new UserPool(this,
   $"{client}UserPool",
   new UserPoolProps
   {
       UserPoolName = $"MyApp_{props.EnvironmentName}_{client}_UserPool"
       // 此处不再设置LambdaTriggers属性
   });
   
   // 手动绑定CustomMessage触发器,指定唯一的构造ID
   userPool.AddCustomMessageTrigger(test, new AddTriggerOptions
   {
       TriggerId = $"CustomMessageCognito-{client}"
   });
}

原理说明

通过AddCustomMessageTrigger传入自定义的TriggerId,CDK会基于这个唯一ID创建辅助Construct,每个用户池的绑定资源名称不再重复,从而解决命名冲突。这种方式完全匹配AWS控制台支持同一Lambda绑定多用户池的场景。

内容的提问来源于stack exchange,提问作者user2612665

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 09:15:39