tom10271
tom10271

Reputation: 4649

How to create a NAT Gateway in CDK and then add route to a private subnet pointing CIDR to it?

I found some examples on setting NAT Instance to private subnet only. I don't want to let AWS create NAT Gateway in each AZs as I am not going to have multi-AZ.

Upvotes: 5

Views: 5919

Answers (1)

ikkjo
ikkjo

Reputation: 785

I might have misunderstood your question. I got things working along the lines of the following (Python). Get the vpc with ec2.Vpc.from_lookup.

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
    )

Upvotes: 4

Related Questions