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

如何在AWS CDK同栈中创建Cognito UserPoolGroup?

Solution for Creating Cognito User Pool Groups in the Same Stack

To create multiple Cognito User Pool Groups alongside your User Pool in the same AWS CDK stack (version 2.64.0), you just need to properly reference the User Pool's ID from the CDK construct you create. The key is using the userPoolId property of the User Pool construct, which CDK resolves as a token during deployment—this works even when the User Pool is being created for the first time, as CDK automatically manages resource dependencies.

Here's the corrected implementation:

import * as cognito from 'aws-cdk-lib/aws-cognito';
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';

export class YourStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    // 1. Create your Cognito User Pool first
    const userPool = new cognito.UserPool(this, 'AppUserPool', {
      // Add your User Pool configuration here (e.g., selfSignUpEnabled, signInAliases, etc.)
      selfSignUpEnabled: false,
      signInAliases: { email: true },
    });

    // 2. Define your groups
    const userPoolGroups = [
      {
        groupName: 'administrators',
        description: 'Members can administer this app - our staff only.',
      },
      {
        groupName: 'foo',
        description: 'bar',
      },
      {
        groupName: 'legends',
        description: 'stars of the game',
      },
    ];

    // 3. Loop through groups to create CfnUserPoolGroup instances
    userPoolGroups.forEach((groupProps) => {
      new cognito.CfnUserPoolGroup(this, `${groupProps.groupName}Group`, {
        userPoolId: userPool.userPoolId, // Use the construct's userPoolId property
        groupName: groupProps.groupName,
        description: groupProps.description,
      });
    });
  }
}

Key Notes:

  • Dependency Management: CDK automatically ensures the User Pool is created before the groups, so you don't have to manually handle ordering.
  • Token Resolution: The userPool.userPoolId value is a CDK token that resolves to the actual User Pool ID during deployment, even on the first run.
  • No External Stacks Needed: This approach keeps all resources in a single stack, avoiding the complexity of cross-stack references.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:03:10