Search code examples
typescriptamazon-web-servicesaws-cdkamazon-vpc

How can I filter subnet by ID for Ec2 CDK?


I'm looking for a way to filter a subnet by Id, from the docs seems like we can use SubnetFilter but I can't parse the subnetFilter to a SubnetSelection:

// Err: Initializer type Subnetfilter Is not assignable to variable type SubnetSelection
const subnets = ec2.SubnetSelection = ec2.SubnetFilter.byIds("subnet-id");

const vpc = ec2.Vpc.fromLookup(this, 'vpc', {
  vpcName: vpc,
  subnets: subnets,
});

I looked into this issue on GitHub but couldn't figure out how to implement it, also tried with ISubnets but haven't found a working example to reference from and believe me I've looked. Sorry if it's a dumb Typescript missunderstanding


Solution

  • Perform a cloud-side lookup of the existing VPC:

    const vpc = ec2.Vpc.fromLookup(this, 'vpc', {
      vpcName: 'my-vpc',
    });
    

    Call its selectSubnets method, passing the subnetFilters option:

    const selection: ec2.SubnetSelection = vpc.selectSubnets({
        subnetFilters: [ec2.SubnetFilter.byIds(["subnet-id"])],
    });