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

如何使用CDK在已创建的Cognito用户池中自动创建测试用户

实现方案

CDK 本身没有提供直接创建 Cognito 用户池测试用户的内置构造,因为用户创建属于运营类操作,不属于基础设施声明的范畴,你可以通过以下两种方式实现需求:

方案1:自定义资源 + Lambda 实现(推荐,随CDK部署自动执行)

这是最稳定的方案,通过CDK自定义资源触发Lambda调用AdminCreateUser接口批量创建用户:

  • 首先编写Lambda处理逻辑,示例(Python):
import boto3
import os
import cfnresponse

cognito_client = boto3.client('cognito-idp')

def lambda_handler(event, context):
    if event['RequestType'] in ['Create', 'Update']:
        user_pool_id = os.environ['USER_POOL_ID']
        # 测试用户列表,可通过自定义资源参数传入
        test_users = [
            {"username": "test_user01", "password": "Test@123456", "email": "test01@example.com"},
            {"username": "test_user02", "password": "Test@123456", "email": "test02@example.com"}
        ]
        for user in test_users:
            # 创建用户,禁止发送欢迎邮件
            cognito_client.admin_create_user(
                UserPoolId=user_pool_id,
                Username=user['username'],
                UserAttributes=[{"Name": "email", "Value": user['email']}, {"Name": "email_verified", "Value": "True"}],
                MessageAction='SUPPRESS'
            )
            # 设置永久密码,跳过首次登录强制改密码逻辑
            cognito_client.admin_set_user_password(
                UserPoolId=user_pool_id,
                Username=user['username'],
                Password=user['password'],
                Permanent=True
            )
    cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
  • 在CDK栈中定义Lambda,为其授予Cognito用户池的操作权限:
    你需要给Lambda的执行角色添加cognito-idp:AdminCreateUser、cognito-idp:AdminSetUserPassword权限,资源指定为你的Cognito用户池ARN即可。
  • 定义CDK自定义资源,关联上述Lambda,部署时会自动触发用户创建逻辑。

方案2:CLI批量脚本(适合本地快速测试)

如果仅需要本地临时创建测试用户,不需要随CDK部署自动执行,可以直接编写AWS CLI批量脚本,示例命令:

# 单个用户创建命令,批量执行即可
aws cognito-idp admin-create-user --user-pool-id <替换为你的用户池ID> --username test_user01 --user-attributes Name=email,Value=test01@example.com Name=email_verified,Value=True --message-action SUPPRESS
aws cognito-idp admin-set-user-password --user-pool-id <替换为你的用户池ID> --username test_user01 --password Test@123456 --permanent

注意:以上方案仅适用于测试环境,生产环境不要预置批量用户,应该由用户自主注册或业务系统按需调用接口创建。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 13:15:04