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

Share VPC among stacks


I am writing the code like this below

export interface MyEc2StackProps extends StackProps {
}
export class MyEc2Stack extends Stack {  
  public readonly vpc: ec2.Vpc;
  constructor(scope: Construct, id: string, props?: MyEc2StackProps) {
    const vpc = ec2.Vpc.fromLookup(this, "myvpc", {
      isDefault: true,
    });
    this.vpc = vpc; #  this can't be compiled

I want to get the vpc and export vpc to use in other stacks.

However this shows the error, IVpc has no property from Vpc....


Solution

  • Switch your member type from ec2.Vpc to ec2.IVpc. You need to do that because ec2.Vpc.fromLookup returns ec2.IVpc. It's not creating a real VPC, but looking one up. Not all operations will be available because it's not being created in your code. But you should be able to use IVpc for most things.