How to create VPC that can be shared across stacks?

前端 未结 2 1486
灰色年华
灰色年华 2021-02-19 19:30

I am trying to wrap my head around how to create a reusable VPC that can be used across multiple stacks using AWS CDK. I want to be able to create different stack per project an

2条回答
  •  后悔当初
    2021-02-19 19:48

    I tried 0x32e0edfb answer and got some problem. so I fix like this.

    VPC Stack

    class VpcStack(core.Stack):
    
        def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
            super().__init__(scope, id, **kwargs)
    
            self.eks_vpc = ec2.Vpc(self, 'eks-vpc',
                cidr='10.1.0.0/16',
                max_azs=2
            )
    

    share VPC to other Stack

    class EksClusterStack(core.Stack):
    
        def __init__(self, scope: core.Construct, id: str, props: ec2.Vpc, **kwargs) -> None:
            super().__init__(scope, id, **kwargs)
    
            cluster = eks.Cluster(self, 'eks-control-plane',
                vpc=props,
                default_capacity=0
            )
    

    and then app.py file

    app = core.App()
    
    vpc_stack = VpcStack(app, 'vpc-stack')
    eks_cluster_stack = EksClusterStack(app, 'eks-cluster', vpc_stack.eks_vpc)
    
    eks_cluster_stack.add_dependency(vpc_stack)
    
    app.synth()
    

    from_lookup is much better used on already existing VPC.

    so I choose to use share-vpcs to share VPC information.

    from_lookup only does the API call once - then, the data is cached in the cdk.context.json file, which should be committed to source control

    That problem was when I recreating the same VPC.

    cdk.context.json didn't update to lasted version. So when I use from_lookup always get old vpc-id.

    I need to use cdk context --clear command and then deploy again. cdk.context.json would get lasted version vpc-id.

    Finally, it can work properly on from_lookup method.

    ref: https://github.com/aws/aws-cdk/blob/master/packages/%40aws-cdk/aws-eks/test/integ.eks-kubectl.lit.ts

    https://docs.aws.amazon.com/cdk/latest/guide/context.html

提交回复
热议问题