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 and then be able to import the VPC that should be assigned to the different stacks. I also want to create this using a good structure where I can deploy different stacks at different times (meaning: I do not want to deploy all stacks at once).
I have tried the following approach but this will create a new VPC per stack which is not what I want to achieve, instead I would like to create my VPC once and then if it already exists it will simply reuse the previous created.
app.ts
import cdk = require('@aws-cdk/core');
import { Stack1 } from '../lib/stack1';
import { Stack2 } from '../lib/stack2';
const app = new cdk.App();
new Stack1(app, "Stack1");
new Stack2(app, "Stack2");
stack1.ts
import cdk = require('@aws-cdk/core');
import { Configurator } from './configurators/configurator'
export class Stack1 extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const configurator = new Configurator(scope, "Stack1");
// later reuse vpc from configurator using configurator.vpc
}
}
stack2.ts
import cdk = require('@aws-cdk/core');
import { Configurator } from './configurators/configurator'
export class Stack2 extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const configurator = new Configurator(scope, "Stack2");
// later reuse vpc from configurator using configurator.vpc
}
}
configurator.ts
import cdk = require('@aws-cdk/core');
import ec2 = require("@aws-cdk/aws-ec2");
export class Configurator {
vpc: ec2.Vpc;
constructor(scope: cdk.Construct, name: string) {
this.vpc = new ec2.Vpc(scope, "MyVPC", {
maxAzs: 3
});
}
}
After doing
cdk synth
cdk deploy Stack1
cdk deploy Stack2
This will create 2 VPCs and not reusing 1 VPC as I would like. I will deploy the stacks to same account and region.
How can I change my approach in order to achieve the output I am looking for? I want to be able to deploy my stacks independently of each other.