使用 CDK 创建 VPC 和简单 Elasticache (Redis) 集群时,堆栈创建失败并出现以下错误:“必须提供参数 SubnetIds。”
我的代码创建一个 VPC、一个缓存子网组(引用 VPC 中的私有子网)和一个 Elasticache/Redis 集群。我希望合成的 CloudFormation 模板包含子网 ID,但它会生成一个空数组。
下面是我的 CDK 堆栈(部分基于 这个示例):
import { Stack, StackProps } from "aws-cdk-lib";
import { Construct } from "constructs";
import {
aws_ec2 as ec2,
aws_elasticache as elasticache
} from "aws-cdk-lib";
export class NetworkStack extends Stack {
public vpc: ec2.Vpc;
public redisCluster: elasticache.CfnCacheCluster;
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
this.vpc = new ec2.Vpc(this, 'Vpc', {
maxAzs: 2,
natGateways: 0,
});
const subnetGroup = new elasticache.CfnSubnetGroup(this, `${id}-subnet-group`, {
description: `List of subnets used for redis cache ${id}`,
subnetIds: this.vpc.privateSubnets.map(function (subnet) {
return subnet.subnetId;
})
});
const securityGroup = new ec2.SecurityGroup(this, `${id}-security-group`, { vpc: this.vpc });
this.redisCluster = new elasticache.CfnCacheCluster(this, `${id}-cluster`, {
cacheNodeType: 'cache.t2.micro',
engine: 'redis',
numCacheNodes: 1,
autoMinorVersionUpgrade: true,
cacheSubnetGroupName: subnetGroup.ref,
vpcSecurityGroupIds: [
securityGroup.securityGroupId
]
});
}
}
如果我查看生成的 CloudFormation 模板,我会看到 Elasticache 子网组的子网 ID 为空数组,而我希望在那里看到 VPC 私有子网 ID。这可能会导致错误。下面是生成的子网组:
"NetworkStacksubnetgroup": {
"Type": "AWS::ElastiCache::SubnetGroup",
"Properties": {
"Description": "List of subnets used for redis cache NetworkStack",
"SubnetIds": []
},
"Metadata": {
"aws:cdk:path": "NetworkStack/NetworkStack-subnet-group"
}
}
有人知道如何解决这个问题吗?
privateSubnets
属性包含通过 NAT 具有互联网出口的子网。由于您将 natGateways
指定为 0
,因此该属性为空 - 您的 VPC 中没有私有子网。
相反,您有
isolatedSubnets
- 有出口/入口。迭代一遍。
指定为0时,请参阅
natGateways
了解默认子网配置的说明:
每个可用区均匀划分 1 个公共子网和 1 个隔离子网
附注仅供参考,创建该
connections
对象在您发布的代码中没有任何效果。