Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding entry to route table with CDK (typescript) when its private subnet already exists

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?

like image 874
dmarch17 Avatar asked Jun 22 '20 23:06

dmarch17


1 Answers

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!

like image 170
robdasilva Avatar answered Oct 16 '22 15:10

robdasilva