Passing VPC from one CDK stack to another

Question:

I am having trouble getting a VPC ID from my shared infrastructure stack to another stack for creating an EC2 instance. Specifically, my error is:

AttributeError: type object 'property' has no attribute '__jsii_type__'

when calling ec2.Instance

Example code

app.py

app = cdk.App()
vpc_stack = VpcStack(app, "VpcStack")
ec2_stack = EC2Stack(app, "EC2Stack", vpc=vpc_stack.vpc)

ec2_stack.py

class EC2Stack(Stack):
    def __init__(self, scope: Construct, construct_id: str, *, vpc=ec2.Vpc, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        ec2.Instance(self, "Instance",
                     vpc=vpc.vpc_id,
                     instance_type=ec2.InstanceType("t3.nano"),
                     machine_image=ec2.MachineImage.latest_amazon_linux()
        )

vpc_stack.py

class VpcStack(Stack):
    vpc = ec2.Vpc
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        vpcName = "MAIN"
        vpcCidr = "10.0.0.0/16"
        natAMI = ec2.GenericLinuxImage({'us-east-2': 'ami-0f9c61b5a562a16af'})

        natInstance = ec2.NatProvider.instance(instance_type=ec2.InstanceType("t3.micro"),machine_image=natAMI)

        vpc = ec2.Vpc(self, str(vpcName), cidr=str(vpcCidr), nat_gateway_provider=natInstance, nat_gateways=1)

I would like to be able to pull the VPC ID into my EC2 stack, to start with, although the ability to share resources across stacks in general is the end goal.

I have tried following the AWS docs here as well as this other wise very helpful blog post here.

Asked By: Caleb Browning

||

Answers:

Try adjusting your vpc_stack.py file to look like

class VpcStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)
        vpcName = "MAIN"
        vpcCidr = "10.0.0.0/16"
        natAMI = ec2.GenericLinuxImage({'us-east-2': 'ami-0f9c61b5a562a16af'})
        natInstance = ec2.NatProvider.instance(instance_type=ec2.InstanceType("t3.micro"),machine_image=natAMI)
        self.vpc = ec2.Vpc(self, str(vpcName), cidr=str(vpcCidr), nat_gateway_provider=natInstance, nat_gateways=1)

Then make sure you’re using the Vpc object on your EC2 instance

class EC2Stack(Stack):
    def __init__(self, scope: Construct, construct_id: str, *, vpc=ec2.Vpc, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        ec2.Instance(self, "Instance",
            vpc=vpc,  # <- vpc instead of vpc.vpc_id
            instance_type=ec2.InstanceType("t3.nano"),
            machine_image=ec2.MachineImage.latest_amazon_linux()
        )
Answered By: maafk
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.