5
votes

Is it possible to add an entry to an imported private subnet's route table with CDK in typescript? I'm importing the VPC with:

import ec2 = require('@aws-cdk/aws-ec2');
vpc = ec2.Vpc.fromVpcAttributes(...)

(docs on fromVpcAttributes: https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.Vpc.html#static-from-wbr-vpc-wbr-attributesscope-id-attrs), and its private subnets are therefore being imported as an array of ISubnets. I want to set up VPC Peering targets/destinations in each of these private subnets' route tables, and the most common way to do this seems to be via the Subnet's addRoute method (https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.Subnet.html#add-wbr-routeid-options). This works when the subnets are newly made, such as here: https://qiita.com/is_ryo/items/66dfe6c4b6dda4bd1eeb, but my private subnets don't have this method, since they were imported as ISubnets. Is there a way to import these subnets as Subnets instead? Or, a better way to add entries in this case?

1

1 Answers

8
votes

I actually got stuck in a similar situation today, which I was able to solve by instantiating new CloudFormation Route resources:

vpc.privateSubnets.forEach(({ routeTable: { routeTableId } }, index) => {
  new CfnRoute(stack, 'PrivateSubnetPeeringConnectionRoute' + index, {
    destinationCidrBlock: '10.0.0.0/16',
    routeTableId,
    vpcPeeringConnectionId: peeringConnection.ref,
  })
})

You will need to know the ID of the peering connection for those routes. In the example above, it's referenced as it's created in the same stack:

const peeringConnection = new CfnVPCPeeringConnection(
  stack,
  'PeeringConnection',
  {
    peerVpcId: peerVpc.vpcId,
    vpcId: vpc.vpcId,
  }
)

Hope this helps!