【问题标题】:Passing VPC from one CDK stack to another将 VPC 从一个 CDK 堆栈传递到另一个
【发布时间】:2023-02-04 02:08:57
【问题描述】:

我无法将 VPC ID 从我的共享基础架构堆栈获取到另一个堆栈以创建 EC2 实例。具体来说,我的错误是:

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

调用 ec2.Instance 时

示例代码

应用程序.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)

我希望能够将 VPC ID 拉入我的 EC2 堆栈,尽管通常跨堆栈共享资源的能力是最终目标。

我尝试关注 AWS 文档 here 以及这篇非常有用的博文 here

【问题讨论】:

    标签: python aws-cdk


    【解决方案1】:

    尝试调整你的vpc_stack.py文件看起来像

    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)
    

    其他一切看起来都不错

    【讨论】:

      猜你喜欢
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 2022-10-17
      • 2013-12-26
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      相关资源
      最近更新 更多