From 8e8a20f34f71ca8e40eec0b1ad242208f3e9cf47 Mon Sep 17 00:00:00 2001 From: Andrew Nowak Date: Mon, 2 Sep 2024 16:41:28 +0100 Subject: [PATCH] vpc construct: only try setting context if unset currently a single stack cannot create multiple vpcs, as each will try to set the context itself, and the subsequent creations will throw errors like Cannot set context after children have been added: MyVpc --- .changeset/dirty-cherries-hug.md | 5 +++++ src/constructs/vpc/vpc.test.ts | 9 +++++++++ src/constructs/vpc/vpc.ts | 10 +++++----- 3 files changed, 19 insertions(+), 5 deletions(-) create mode 100644 .changeset/dirty-cherries-hug.md diff --git a/.changeset/dirty-cherries-hug.md b/.changeset/dirty-cherries-hug.md new file mode 100644 index 0000000000..aa889ff2a8 --- /dev/null +++ b/.changeset/dirty-cherries-hug.md @@ -0,0 +1,5 @@ +--- +"@guardian/cdk": patch +--- + +Fix bug preventing creation of multiple VPCs in single stack diff --git a/src/constructs/vpc/vpc.test.ts b/src/constructs/vpc/vpc.test.ts index 04e358d744..23986704ff 100644 --- a/src/constructs/vpc/vpc.test.ts +++ b/src/constructs/vpc/vpc.test.ts @@ -11,4 +11,13 @@ describe("The GuVpc construct", () => { new GuVpc(stack, "MyVpc"); expect(Template.fromStack(stack).toJSON()).toMatchSnapshot(); }); + + it("should be possible to create two vpcs in the same stack", () => { + const stack = simpleGuStackForTesting({ + stack: "test-stack", + env: { region: "eu-west-1", account: "000000000000" }, + }); + new GuVpc(stack, "MyVpc"); + new GuVpc(stack, "MyOtherVpc"); + }); }); diff --git a/src/constructs/vpc/vpc.ts b/src/constructs/vpc/vpc.ts index 0884339086..32c0d8bd45 100644 --- a/src/constructs/vpc/vpc.ts +++ b/src/constructs/vpc/vpc.ts @@ -61,11 +61,11 @@ export class GuVpc extends Vpc { ); } - node.setContext(`availability-zones:account=${account}:region=eu-west-1`, [ - "eu-west-1a", - "eu-west-1b", - "eu-west-1c", - ]); + const contextKey = `availability-zones:account=${account}:region=eu-west-1`; + + if (node.tryGetContext(contextKey) === undefined) { + node.setContext(contextKey, ["eu-west-1a", "eu-west-1b", "eu-west-1c"]); + } } constructor(scope: GuStack, id: string, props?: GuVpcProps) {