在 AWS CDK 中,创建 PublicSubnet 并没有直接创建互联网网关。互联网网关是用来连接公共子网和互联网的组件,需要另外创建,并将其与公共子网关联起来。
下面是一个创建 PublicSubnet 并关联互联网网关的示例代码:
from aws_cdk import core
from aws_cdk import aws_ec2 as ec2
class MyStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
# 创建 VPC
vpc = ec2.Vpc(self, "MyVpc", cidr="10.0.0.0/16")
# 创建公共子网
public_subnet = ec2.PublicSubnet(self, "MyPublicSubnet",
vpc_id=vpc.vpc_id,
cidr_block="10.0.0.0/24",
availability_zone=vpc.availability_zones[0],
map_public_ip_on_launch=True # 自动分配公共 IP 地址
)
# 创建互联网网关
internet_gateway = ec2.CfnInternetGateway(self, "MyInternetGateway")
# 将互联网网关附加到 VPC
ec2.CfnVPCGatewayAttachment(self, "MyGatewayAttachment",
vpc_id=vpc.vpc_id,
internet_gateway_id=internet_gateway.ref
)
# 将公共子网与互联网网关关联
route_table = ec2.CfnRouteTable(self, "MyRouteTable",
vpc_id=vpc.vpc_id
)
ec2.CfnSubnetRouteTableAssociation(self, "MySubnetRouteTableAssociation",
subnet_id=public_subnet.subnet_id,
route_table_id=route_table.ref
)
ec2.CfnRoute(self, "MyRoute",
route_table_id=route_table.ref,
destination_cidr_block="0.0.0.0/0",
gateway_id=internet_gateway.ref
)
在上面的示例中,我们创建了一个 VPC 和一个公共子网,然后创建了一个互联网网关,并将其附加到 VPC 中。最后,我们将公共子网与互联网网关关联,并为该子网创建了一个默认路由,以便流量可以从该子网中到达互联网。
请根据您的实际需求进行适当的调整和修改。