如何通过AWS CDK在非默认VPC中创建Serverless Aurora的CfnDBCluster?
问题根源与解决方案
你遇到的问题核心是没有为CfnDBCluster指定部署目标子网,导致CloudFormation默认将Aurora集群放到了区域的默认VPC中,而你的安全组属于自定义创建的VPC,两者VPC不一致就触发了那个报错。
关键修正步骤
对于CDK的L1构造rds.CfnDBCluster,必须显式配置vpc_subnet_ids参数,指定集群要部署到哪个VPC的子网里。下面是修正后的完整代码:
from aws_cdk import ( core, aws_rds as rds, aws_ec2 as ec2 ) class CdkAuroraStack(core.Stack): def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # 创建自定义VPC vpc = ec2.Vpc(self, "VPC") # 在自定义VPC内创建安全组 sg = ec2.SecurityGroup(self, "SecurityGroup", vpc = vpc, allow_all_outbound = True ) # 获取自定义VPC的私有子网ID(推荐将数据库部署在私有子网,避免公网暴露) private_subnet_ids = [subnet.subnet_id for subnet in vpc.private_subnets] # 创建Aurora Serverless集群,添加vpc_subnet_ids配置 cluster = rds.CfnDBCluster(self, "AuroraDB", engine="aurora", engine_mode="serverless", master_username="admin", master_user_password="password", database_name="databasename", vpc_security_group_ids=[ sg.security_group_id ], # 关键配置:指定集群所属的自定义VPC子网 vpc_subnet_ids=private_subnet_ids )
额外建议
你当前使用的是CDK 1.19.0(较旧版本),如果条件允许,建议升级到最新稳定版本,使用CDK的L2构造rds.ServerlessCluster,它会自动处理VPC子网选择、安全组关联等细节,大幅减少手动配置的错误:
# L2构造示例(需要较新版本CDK支持) from aws_cdk import ( core, aws_rds as rds, aws_ec2 as ec2 ) class CdkAuroraStack(core.Stack): def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) vpc = ec2.Vpc(self, "VPC") sg = ec2.SecurityGroup(self, "SecurityGroup", vpc = vpc, allow_all_outbound = True ) # 使用L2构造创建Serverless Aurora cluster = rds.ServerlessCluster(self, "AuroraDB", engine=rds.DatabaseClusterEngine.AURORA, credentials=rds.Credentials.from_username("admin", password=core.SecretValue.plain_text("password")), default_database_name="databasename", vpc=vpc, security_groups=[sg] )
(注意:生产环境中不要用SecretValue.plain_text存储密码,建议使用Secrets Manager或者参数存储)
内容的提问来源于stack exchange,提问作者justaguy
相关产品推荐
相关产品推荐

