Skip to content

Commit

Permalink
vpc construct: only try setting context if unset
Browse files Browse the repository at this point in the history
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
  • Loading branch information
andrew-nowak committed Sep 2, 2024
1 parent 10cad8d commit 8e8a20f
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/dirty-cherries-hug.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@guardian/cdk": patch
---

Fix bug preventing creation of multiple VPCs in single stack
9 changes: 9 additions & 0 deletions src/constructs/vpc/vpc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
});
10 changes: 5 additions & 5 deletions src/constructs/vpc/vpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 8e8a20f

Please sign in to comment.