How to create VPC that can be shared across stacks?

前端 未结 2 1499
灰色年华
灰色年华 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 20:10

    If you intend to reuse the VPC in different stacks, I'd recommend placing it in a separate stack, since your VPC stack will have a different lifecycle than your application stacks.

    Here's what I'd do. I hope you don't mind a bit of Python :)

    First, define your VPC in VpcStack:

    class VpcStack(core.Stack):
        def __init__(self, app: core.App, id: str, **kwargs) -> None:
            super().__init__(app, id, **kwargs)
            aws_ec2.Vpc(self, 'MyVPC', max_azs=3)
    

    Then look it up in another stack:

    class Stack1(core.Stack):
        def __init__(self, app: core.App, id: str, **kwargs) -> None:
            super().__init__(app, id, **kwargs)
            # Lookup the VPC named 'MyVPC' created in stack 'vpc-stack'
            my_vpc = aws_ec2.Vpc.from_lookup(self, 'MyVPC', vpc_name=f'vpc-stack/MyVPC')
            # You can now use the VPC in ECS cluster, etc.
    

    And this would be your cdk_app.py:

    app = core.App()
    vpc = VpcStack(app, 'vpc-stack')
    stack1 = Stack1(app, 'stack1')
    

提交回复
热议问题