如何在CDK中创建NAT网关,然后将路由添加到将CIDR指向它的专用子网?

时间:2020-09-22 06:48:49

标签: amazon-cloudformation aws-cdk clouddevelopmentkit

我找到了一些将NAT实例设置为仅专用子网的示例。我不想让AWS在每个可用区中创建NAT网关,因为我将没有多可用区。

1 个答案:

答案 0 :(得分:1)

我可能误解了您的问题。我按照以下(Python)的方式工作。使用 ec2.Vpc.from_lookup 获取 vpc。

allocation_id = 'eipalloc-xxx1'

nat_gateway = ec2.CfnNatGateway(
    self,
    'My-Nat-Gateway',
    allocation_id = allocation_id,
    subnet_id = 'subnet-1234' # the ID of the first default subnet in the VPC, in my case it was ok not to do it for all subnets
)

ip_range_index_offset = 3

for i, az in enumerate(vpc.availability_zones):
    sub_net = ec2.PrivateSubnet(
        self,
        id = 'private-subnet-' + str(i),
        availability_zone = az,
        cidr_block = '123.12.'+ str(16 * (i+ip_range_index_offset)) +'.0/20', # there is likely a better way to do this
        vpc_id = vpc.vpc_id,
    )

    route_table_entry = ec2.CfnRoute(
        self,
        id = 'route-table-entry' + str(i),
        route_table_id  = sub_net.route_table.route_table_id,
        destination_cidr_block = '0.0.0.0/0',
        nat_gateway_id = nat_gateway.ref

    )