我创建了一个VPC
vpc = ec2.Vpc(
self,
VPC_CONFIG["vpc_name"],
cidr=VPC_CONFIG["cidr"],
nat_gateways=VPC_CONFIG["nat_gateways"],
subnet_configuration=[],
enable_dns_support=True,
enable_dns_hostnames=True,
)
接下来,我创建了一些漂亮的子网
for subnet in SUBNETS:
subnet_created = ec2.CfnSubnet(
self,
subnet["name"],
vpc_id=vpc.vpc_id,
cidr_block=subnet["cidr_block"],
availability_zone=subnet["availability_zone"],
tags=[{"key": "Name", "value": subnet["name"]}],
map_public_ip_on_launch=True,
)
接下来,我创建了一个带有服务的集群。 我想在我的私有子网中分配我的服务,所以我尝试了
cluster = ecs.Cluster(self, "MyCluster", vpc=vpc)
task_definition = ecs.FargateTaskDefinition(
self,
f"{VPC_CONFIG['vpc_name']}-MyFargateTaskDefinition",
memory_limit_mib=512, # 512 is 0.5 GB
cpu=256, # 256 is 0.25 vCPU
)
task_definition.add_container(
f"{VPC_CONFIG['vpc_name']}-MyBackendContainer",
image=ecs.ContainerImage.from_registry(BACKEND_CONFIG["docker_image"]),
memory_reservation_mib=256,
)
print("-"*10, ">", private_subnet, ":(")
# ----------> <aws_cdk.aws_ec2.CfnSubnet object at 0x000001DB96834890> :(
service = ecs.FargateService(
self,
"MyService",
cluster=cluster,
task_definition=task_definition,
desired_count=1,
assign_public_ip=False,
vpc_subnets=ec2.SubnetSelection(subnets=[private_subnet]),
security_groups=[private_sec_gp],
)
这里的问题是我运行
cdk synth
,我检查了我的文件,发现vpc_subnets
是空的
所以,经过几个小时的疲惫研究,我发现
ec2.SubnetSelection(subnets=)
需要 Sequence[ISubnet]
类型,而我有 CfnSubnet
。我不确定这是否是问题所在。我在这里省略了一些代码,但我认为它与解决这个问题无关:(
我被困住了,因为当我运行
cdk deploy
cloudFormation 时会这样说
MyService/Service (MyServiceB4132EDA) Resource handler returned message: "Invalid request provided: CreateService error: subnets can not be empty. (Service: AmazonECS; Status Code: 400; Error Code: InvalidParameterException; Request ID: 1643b0eb-61dc-45c8-800a-989ce8ab6c0f; Proxy: null)" (RequestToken: 2ebb2a5c-c39e-03b1-f5e2-6f6284360b97, HandlerErrorCode: InvalidRequest)
以下是直接在 VPC 构造中配置子网的示例:
subnet_config = [
ec2.SubnetConfiguration(
name="PublicSubnet",
subnet_type=ec2.SubnetType.PUBLIC,
cidr_mask=21,
),
ec2.SubnetConfiguration(
name="PrivateSubnet",
subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS,
cidr_mask=19,
),
ec2.SubnetConfiguration(
name="IsolatedSubnet",
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED,
cidr_mask=22,
),
ec2.SubnetConfiguration(
name="VpnSubnet",
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED,
cidr_mask=27,
),
]
# Create the VPC using the L2 construct
self.vpc = ec2.Vpc(
scope=self,
id="Vpc",
max_azs=2,
nat_gateways=0,
subnet_configuration=subnet_config,
ip_addresses=ec2.IpAddresses.cidr(cidr_block="10.10.0.0/16"),
)
然后你可以像这样访问它:
ec2.SubnetSelection(subnet_group_name="PublicSubnet")
ec2.SubnetSelection(subnet_group_name="VpnSubnet")
...