-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathvpc.ts
786 lines (722 loc) · 26.7 KB
/
vpc.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
// Copyright 2016-2022, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as aws from "@pulumi/aws";
import * as pulumi from "@pulumi/pulumi";
import * as schema from "../schema-types";
import { getSubnetSpecsLegacy } from "./subnetDistributorLegacy";
import * as vpcConverters from "./vpcConverters";
import { SubnetSpec, SubnetSpecPartial, validatePartialSubnetSpecs } from "./subnetSpecs";
import {
getSubnetSpecs,
getSubnetSpecsExplicit,
validateAndNormalizeSubnetInputs,
NormalizedSubnetInputs,
ExplicitSubnetSpecInputs,
} from "./subnetDistributorNew";
import { Netmask } from "netmask";
interface VpcData {
vpc: aws.ec2.Vpc;
subnets: aws.ec2.Subnet[];
vpcEndpoints: aws.ec2.VpcEndpoint[];
routeTables: aws.ec2.RouteTable[];
routes: aws.ec2.Route[];
routeTableAssociations: aws.ec2.RouteTableAssociation[];
igw: aws.ec2.InternetGateway;
natGateways: aws.ec2.NatGateway[];
eips: aws.ec2.Eip[];
subnetLayout: pulumi.Output<schema.ResolvedSubnetSpecOutputs[]>;
publicSubnetIds: pulumi.Output<string>[];
privateSubnetIds: pulumi.Output<string>[];
isolatedSubnetIds: pulumi.Output<string>[];
vpcId: pulumi.Output<string>;
}
export class Vpc extends schema.Vpc<VpcData> {
constructor(name: string, args: schema.VpcArgs, opts: pulumi.ComponentResourceOptions = {}) {
super(name, args, opts);
const data = pulumi.output(this.getData());
this.vpc = data.vpc;
this.subnets = data.subnets;
this.routeTables = data.routeTables;
this.routes = data.routes;
this.routeTableAssociations = data.routeTableAssociations;
this.internetGateway = data.igw;
this.natGateways = data.natGateways;
this.eips = data.eips;
this.subnetLayout = data.subnetLayout.apply(vpcConverters.toResolvedSubnetSpecOutputs);
this.privateSubnetIds = data.privateSubnetIds;
this.publicSubnetIds = data.publicSubnetIds;
this.isolatedSubnetIds = data.isolatedSubnetIds;
this.vpcEndpoints = data.vpcEndpoints;
this.vpcId = data.vpcId;
}
protected async initialize(props: {
name: string;
args: schema.VpcArgs;
opts: pulumi.ComponentResourceOptions;
}): Promise<VpcData> {
Vpc.validateVpcArgs(props.args);
const { name, args } = props;
if (args.availabilityZoneNames && args.numberOfAvailabilityZones) {
throw new Error(
"Only one of [availabilityZoneNames] and [numberOfAvailabilityZones] can be specified",
);
}
const availabilityZones =
args.availabilityZoneNames ?? (await this.getDefaultAzs(args.numberOfAvailabilityZones));
const natGatewayStrategy: schema.NatGatewayStrategyInputs =
args.natGateways?.strategy ?? "OnePerAz";
const allocationIds = args.natGateways?.elasticIpAllocationIds ?? [];
validateEips(natGatewayStrategy, allocationIds, availabilityZones);
const subnetStrategy = args.subnetStrategy ?? "Legacy";
const sharedTags = { Name: name, ...args.tags };
const cidrBlock = Vpc.decideCidrBlockVpcInput(args);
const {
vpc,
subnets: { subnetSpecs, subnetLayout },
} = this.createInnerVpc(
name,
subnetStrategy,
availabilityZones,
natGatewayStrategy,
args,
cidrBlock,
sharedTags,
);
// We unconditionally create the IGW (even if it's not needed because we
// only have isolated subnets) because AWS does not charge for it, and
// therefore there's no harm in adding it, whereas conditional resources
// must be declared in the constructor, which significantly complicates the
// code.
const igw = new aws.ec2.InternetGateway(
`${name}`,
{
vpcId: vpc.id,
tags: sharedTags,
},
{ parent: vpc, dependsOn: [vpc] },
);
const vpcEndpoints: aws.ec2.VpcEndpoint[] = [];
const subnets: aws.ec2.Subnet[] = [];
const routeTables: aws.ec2.RouteTable[] = [];
const routeTableAssociations: aws.ec2.RouteTableAssociation[] = [];
const routes: aws.ec2.Route[] = [];
const natGateways: aws.ec2.NatGateway[] = [];
const eips: aws.ec2.Eip[] = [];
const publicSubnetIds: pulumi.Output<string>[] = [];
const privateSubnetIds: pulumi.Output<string>[] = [];
const isolatedSubnetIds: pulumi.Output<string>[] = [];
args.vpcEndpointSpecs?.forEach((spec) => {
const vpcEndpoint = new aws.ec2.VpcEndpoint(
spec.serviceName,
{
autoAccept: spec.autoAccept,
policy: spec.policy,
privateDnsEnabled: spec.privateDnsEnabled,
routeTableIds: spec.routeTableIds,
securityGroupIds: spec.securityGroupIds,
subnetIds: spec.subnetIds,
tags: spec.tags,
vpcEndpointType: spec.vpcEndpointType,
vpcId: vpc.id,
serviceName: spec.serviceName,
},
{
parent: vpc,
dependsOn: [vpc],
},
);
});
for (let i = 0; i < availabilityZones.length; i++) {
subnetSpecs
.filter((x) => x.azName === availabilityZones[i] && x.type !== "Unused")
.sort(compareSubnetSpecs)
.forEach((spec) => {
const subnet = new aws.ec2.Subnet(
spec.subnetName,
{
vpcId: vpc.id,
availabilityZone: spec.azName,
mapPublicIpOnLaunch: spec.type.toLowerCase() === "public",
cidrBlock: spec.cidrBlock,
tags: {
...sharedTags,
...spec.tags,
Name: spec.subnetName,
SubnetType: spec.type,
},
},
{ parent: vpc, dependsOn: [vpc] },
);
subnets.push(subnet);
if (spec.type.toLowerCase() === "public") {
publicSubnetIds.push(subnet.id);
} else if (spec.type.toLowerCase() === "private") {
privateSubnetIds.push(subnet.id);
} else {
isolatedSubnetIds.push(subnet.id);
}
const routeTable = new aws.ec2.RouteTable(
spec.subnetName,
{
vpcId: vpc.id,
tags: {
...sharedTags,
Name: spec.subnetName,
SubnetType: spec.type,
},
},
{ parent: subnet, dependsOn: [subnet] },
);
routeTables.push(routeTable);
const routeTableAssoc = new aws.ec2.RouteTableAssociation(
spec.subnetName,
{
routeTableId: routeTable.id,
subnetId: subnet.id,
},
{ parent: routeTable, dependsOn: [routeTable] },
);
routeTableAssociations.push(routeTableAssoc);
if (
spec.type.toLowerCase() === "public" &&
shouldCreateNatGateway(natGatewayStrategy, natGateways.length, i)
) {
const createEip = allocationIds.length === 0;
if (createEip) {
const eip = new aws.ec2.Eip(
`${name}-${i + 1}`,
{
tags: {
...args.tags,
Name: `${name}-${i + 1}`,
},
},
{ parent: subnet, dependsOn: [subnet] },
);
eips.push(eip);
}
const natGateway = new aws.ec2.NatGateway(
`${name}-${i + 1}`,
{
subnetId: subnet.id,
allocationId: createEip ? eips[i].allocationId : allocationIds[i],
tags: {
...args.tags,
Name: `${name}-${i + 1}`,
},
},
{ parent: subnet, dependsOn: [subnet] },
);
natGateways.push(natGateway);
}
if (spec.type.toLowerCase() === "public") {
// Public subnets communicate directly with the internet via the Internet Gateway.
const route = new aws.ec2.Route(
spec.subnetName,
{
routeTableId: routeTable.id,
gatewayId: igw.id,
destinationCidrBlock: "0.0.0.0/0",
},
{ parent: routeTable, dependsOn: [routeTable] },
);
routes.push(route);
} else if (spec.type.toLowerCase() === "private") {
if (natGatewayStrategy.toLowerCase() !== "none") {
// Private subnets communicate indirectly with the internet via a NAT Gateway.
// Because we've already validated the strategy and have ensured that public subnets are created
// first via the sort above, we know the necessary NAT Gateway already exists.
const natGatewayId =
natGatewayStrategy.toLowerCase() === "single"
? natGateways[0].id
: natGateways[i].id;
const route = new aws.ec2.Route(
spec.subnetName,
{
routeTableId: routeTable.id,
natGatewayId,
destinationCidrBlock: "0.0.0.0/0",
},
{ parent: routeTable, dependsOn: [routeTable] },
);
routes.push(route);
}
}
// Isolated subnets do not have any route to the internet and therefore need no route created.
});
}
return {
vpc,
vpcEndpoints,
subnets,
igw,
routeTables,
routeTableAssociations,
routes,
natGateways,
eips,
subnetLayout: pulumi.output(subnetLayout).apply(vpcConverters.toResolvedSubnetSpecOutputs),
privateSubnetIds,
publicSubnetIds,
isolatedSubnetIds,
vpcId: vpc.id,
};
}
// Internal. Exported for testing.
public static validateVpcArgs(args: schema.VpcArgs) {
if (args.ipv4IpamPoolId !== undefined) {
if (args.cidrBlock !== undefined && args.ipv4NetmaskLength !== undefined) {
throw new Error("Only one of 'cidrBlock', 'ipv4NetmaskLength' is allowed.");
}
if (args.ipv4NetmaskLength === undefined && args.cidrBlock === undefined) {
throw new Error(
"If 'ipv4IpamPoolId' is specified, 'ipv4NetmaskLength' or 'cidrBlock' must also be specified.",
);
}
}
}
// Decide the cidrBlock input parameter for the underlying aws.ec2.Vpc resource.
private static decideCidrBlockVpcInput(args: schema.VpcArgs): string | undefined {
// Respect the user-provided value, if any.
if (args.cidrBlock !== undefined) {
return args.cidrBlock;
}
// If the user wants to use an IPAM pool without specifying a cidrBlock, they must also define ipv4netMaskLength
// that instructs how the IPAM pool should allocate the cidrBlock. In this case the should not assume any defaults.
if (args.ipv4IpamPoolId !== undefined) {
return undefined;
}
// Historically this default was used when left unspecified.
return "10.0.0.0/16";
}
private createInnerVpc(
name: string,
subnetStrategy: schema.SubnetAllocationStrategyInputs,
availabilityZones: string[],
natGatewayStrategy: schema.NatGatewayStrategyInputs,
args: schema.VpcArgs,
cidrBlock: string | undefined,
sharedTags: pulumi.Input<Record<string, pulumi.Input<string>>>,
): {
vpc: aws.ec2.Vpc;
subnets: {
subnetSpecs: SubnetSpecPartial[];
subnetLayout: pulumi.Output<schema.ResolvedSubnetSpecOutputs[]>;
};
} {
if (cidrBlock) {
// If cidrBlock is known because the user provided it, validations should run as early as possible. Failing
// validations will short-circuit trying to create the inner aws.ec2.Vpc resource.
const subnets = this.decideAndValidateSubnetSpecs(
name,
subnetStrategy,
availabilityZones,
natGatewayStrategy,
args,
cidrBlock,
);
const vpc = new aws.ec2.Vpc(
name,
{
...args,
cidrBlock,
tags: sharedTags,
},
{ parent: this },
);
return { vpc, subnets };
} else {
// If cidrBlock is not yet known, validations will run after the creation of the aws.ec2.Vpc resource and will be
// based on the dynamically decided cidrBlock value. If these validations fail, subnet specs and layout will have
// failing outputs which will short-circuit creating the subnets.
const vpc = new aws.ec2.Vpc(
name,
{
...args,
cidrBlock,
tags: sharedTags,
},
{ parent: this },
);
const subnets = this.decideAndValidateSubnetSpecs(
name,
subnetStrategy,
availabilityZones,
natGatewayStrategy,
args,
vpc.cidrBlock,
);
return { vpc, subnets };
}
}
private decideAndValidateSubnetSpecs(
name: string,
subnetStrategy: schema.SubnetAllocationStrategyInputs,
availabilityZones: string[],
natGatewayStrategy: schema.NatGatewayStrategyInputs,
args: schema.VpcArgs,
actualCidrBlock: pulumi.Input<string>,
): {
subnetSpecs: SubnetSpecPartial[];
subnetLayout: pulumi.Output<schema.ResolvedSubnetSpecOutputs[]>;
} {
const { subnetSpecs: decidedSpecs, subnetLayout } = this.decideSubnetSpecs(
name,
actualCidrBlock,
subnetStrategy,
availabilityZones,
args,
);
const subnetSpecs = validatePartialSubnetSpecs(decidedSpecs, (subnetSpecs) => {
validateSubnets(subnetSpecs, getOverlappingSubnets);
// Only prompt cidrBlock is validated; probably OK as non-prompt cidrBlock implies that ipv4NetmaskLength was set
// to allocate the cidrBlock via IPAM.
if (subnetStrategy === "Exact" && typeof actualCidrBlock === "string") {
validateNoGaps(actualCidrBlock, subnetSpecs);
}
validateNatGatewayStrategy(natGatewayStrategy, subnetSpecs);
});
return { subnetSpecs, subnetLayout };
}
private decideSubnetSpecs(
name: string,
cidrBlock: pulumi.Input<string>,
subnetStrategy: schema.SubnetAllocationStrategyInputs,
availabilityZones: string[],
args: {
readonly subnetSpecs?: schema.SubnetSpecInputs[];
readonly subnetStrategy?: schema.SubnetAllocationStrategyInputs;
readonly availabilityZoneCidrMask?: number;
},
): {
subnetSpecs: SubnetSpecPartial[];
subnetLayout: pulumi.Output<schema.ResolvedSubnetSpecOutputs[]>;
} {
const parsedSpecs: NormalizedSubnetInputs = validateAndNormalizeSubnetInputs(
args.subnetSpecs,
availabilityZones.length,
);
const subnetSpecs = (() => {
const a = Vpc.pickSubnetAllocator(parsedSpecs, subnetStrategy);
switch (a.allocator) {
case "LegacyAllocator":
if (typeof cidrBlock !== "string") {
throw new Error(
`Dynamically allocated cidrBlock ranges are not supported with subnetStrategy="Legacy". ` +
`"Try using subnetStrategy="Auto"`,
);
}
const legacySubnetSpecs = getSubnetSpecsLegacy(
name,
cidrBlock,
availabilityZones,
parsedSpecs?.normalizedSpecs,
);
return legacySubnetSpecs;
case "ExplicitAllocator":
return getSubnetSpecsExplicit(name, availabilityZones, a.specs);
case "NewAllocator":
default:
return getSubnetSpecs(
name,
cidrBlock,
availabilityZones,
parsedSpecs?.normalizedSpecs,
args.availabilityZoneCidrMask,
);
}
})();
const subnetLayout: pulumi.Output<schema.ResolvedSubnetSpecOutputs[]> =
subnetStrategy === "Legacy" || parsedSpecs?.normalizedSpecs === undefined
? pulumi
.output(subnetSpecs)
.apply((ss) => extractSubnetSpecInputFromLegacyLayout(ss, name, availabilityZones))
.apply(vpcConverters.toResolvedSubnetSpecOutputs)
: pulumi
.output(parsedSpecs?.normalizedSpecs)
.apply(vpcConverters.toResolvedSubnetSpecOutputs);
const verifiedSubnetLayout = pulumi.jsonStringify(subnetLayout).apply((sl) => {
// Only warn if they're using a custom, non-explicit layout and haven't specified a strategy.
if (
args.subnetStrategy === undefined &&
parsedSpecs !== undefined &&
parsedSpecs.isExplicitLayout === false
) {
pulumi.log.warn(
`The default subnetStrategy will change from "Legacy" to "Auto" in the next major version. Please specify the subnetStrategy explicitly. The current subnet layout can be specified via "Auto" as:\n\n${sl}`,
this,
);
}
return subnetLayout;
});
return { subnetLayout: verifiedSubnetLayout, subnetSpecs };
}
async getDefaultAzs(azCount?: number): Promise<string[]> {
const desiredCount = azCount ?? 3;
const result = await aws.getAvailabilityZones(undefined, { parent: this });
if (result.names.length < desiredCount) {
throw new Error(
`The configured region for this provider does not have at least ${desiredCount} Availability Zones. Either specify an explicit list of zones in availabilityZoneNames or choose a region with at least ${desiredCount} AZs.`,
);
}
return result.names.slice(0, desiredCount);
}
// Internal. Exported for testing.
public static pickSubnetAllocator(
parsedSpecs: NormalizedSubnetInputs,
subnetStrategy: schema.SubnetAllocationStrategyInputs,
):
| { allocator: "LegacyAllocator" | "NewAllocator" }
| { allocator: "ExplicitAllocator"; specs: ExplicitSubnetSpecInputs[] } {
if (parsedSpecs === undefined) {
return subnetStrategy === "Auto"
? { allocator: "NewAllocator" }
: { allocator: "LegacyAllocator" };
}
if (subnetStrategy === "Legacy") {
return { allocator: "LegacyAllocator" };
}
if (parsedSpecs.isExplicitLayout) {
return { allocator: "ExplicitAllocator", specs: parsedSpecs.normalizedSpecs };
}
return { allocator: "NewAllocator" };
}
}
export function extractSubnetSpecInputFromLegacyLayout(
subnetSpecs: SubnetSpec[],
vpcName: string,
availabilityZones: string[],
): schema.SubnetSpecInputs[] {
const singleAzLength = subnetSpecs.length / availabilityZones.length;
function extractName(subnetName: string, type: schema.SubnetTypeInputs) {
const withoutVpcPrefix = subnetName.replace(`${vpcName}-`, "");
const subnetSpecName = withoutVpcPrefix.replace(/-\d+$/, "");
// If the spec name is the same as the type, it doesn't need to be specified.
if (subnetSpecName === type.toLowerCase()) {
return {};
}
return { subnetName: subnetSpecName };
}
const subnetSpecInputs: schema.SubnetSpecInputs[] = [];
// Just look at the first AZ's subnets, since they're all the same pattern.
let previousNetmask: Netmask | undefined;
const singleAzSubnets = subnetSpecs.slice(0, singleAzLength);
for (const subnet of singleAzSubnets) {
const netmask = new Netmask(subnet.cidrBlock);
if (previousNetmask !== undefined) {
const gaps = findSubnetGap(previousNetmask, netmask);
for (const gap of gaps) {
subnetSpecInputs.push({
type: "Unused",
cidrMask: gap.bitmask,
});
}
}
subnetSpecInputs.push({
type: subnet.type,
...extractName(subnet.subnetName, subnet.type),
cidrMask: netmask.bitmask,
...(subnet.tags ? { tags: subnet.tags } : {}),
});
previousNetmask = netmask;
}
return subnetSpecInputs;
}
/** Find the subnets required to fill the gap between two subnets. */
export function findSubnetGap(a: Netmask, b: Netmask): Netmask[] {
// Normalise start to be before the end.
const [start, end] = a.netLong < b.netLong ? [a, b] : [b, a];
// Where the start and end differ by more than 1 bit there may be multiple subnets required to fill the gap.
const gaps: Netmask[] = [];
let previous = a;
let next = start.next();
while (next.netLong < end.netLong) {
// Try to find widest possible gap that doesn't overlap the start or end subnet.
while (true) {
const nextWiderGap = new Netmask(`${next.base}/${next.bitmask - 1}`);
if (nextWiderGap.contains(previous.last) || nextWiderGap.contains(end.first)) {
break;
}
next = nextWiderGap;
}
gaps.push(next);
previous = next;
next = next.next();
}
return gaps;
}
export function validateEips(
natGatewayStrategy: schema.NatGatewayStrategyInputs,
eips: pulumi.Input<string>[] | undefined,
availabilityZones: string[] = [],
) {
// We are strict about matching NAT Gateway strategies with the number of supplied EIPs (if supplied) because if
// EIPs are supplied, we are assuming the user has a scenario where all outbound traffic from the VPC must come
// from known IP addresses, e.g. because they are hitting a data center-based service with a firewall that must
// allowlist specific IP addresses. Assuming this is the user's scenario, e.g. we have 3 AZs, and only 2 EIPs
// specified, 1/3 of the traffic coming from the VPC will be seemingly randomly rejected, which is a difficult
// and frustrating problem to debug. Therefore, we feel it's better to be strict about the acceptable inputs to
// avoid potentially confusing problems in production.
switch (natGatewayStrategy.toLowerCase()) {
case "none":
if (eips?.length ?? 0 !== 0) {
throw new Error(
`Elastic IP allocation IDs cannot be specified when NAT Gateway strategy is '${natGatewayStrategy}'.`,
);
}
break;
case "single":
if (eips && eips.length > 1) {
throw new Error(
`Exactly one Elastic IP may be specified when NAT Gateway strategy is '${natGatewayStrategy}'.`,
);
}
break;
case "oneperaz":
if (eips && eips.length > 0 && eips.length !== availabilityZones.length) {
throw new Error(
`The number of Elastic IPs, if specified, must match the number of availability zones for the VPC (${availabilityZones.length}) when NAT Gateway strategy is '${natGatewayStrategy}'`,
);
}
break;
default:
throw new Error(`Unknown NatGatewayStrategy '${natGatewayStrategy}'`);
}
}
export function validateNatGatewayStrategy(
natGatewayStrategy: schema.NatGatewayStrategyInputs,
subnets: SubnetSpec[],
) {
// This logic assumes that the same subnets exist in every AZ:
switch (natGatewayStrategy.toLowerCase()) {
case "oneperaz":
case "single":
if (
subnets.some((x) => x.type.toLowerCase() === "public") &&
subnets.some((x) => x.type.toLowerCase() === "private")
) {
return;
}
throw new Error(
"If NAT Gateway strategy is 'OnePerAz' or 'Single', both private and public subnets must be declared. The private subnet creates the need for a NAT Gateway, and the public subnet is required to host the NAT Gateway resource.",
);
case "none":
break;
default:
throw new Error(`Unknown NAT Gateway strategy '${natGatewayStrategy}'`);
}
}
export function shouldCreateNatGateway(
strategy: schema.NatGatewayStrategyInputs,
numGateways: number,
azIndex: number,
) {
switch (strategy.toLowerCase()) {
case "none":
return false;
case "single":
return numGateways < 1;
case "oneperaz":
return numGateways < azIndex + 1;
default:
throw new Error(`Unknown NatGatewayStrategy "${strategy}"`);
}
}
export function compareSubnetSpecs(
spec1: Omit<SubnetSpec, "cidrBlock">,
spec2: Omit<SubnetSpec, "cidrBlock">,
): number {
if (spec1.type === spec2.type) {
return 0;
}
// Public always comes first
if (spec1.type.toLowerCase() === "public") {
return -1;
}
if (spec1.type.toLowerCase() === "private" && spec2.type.toLowerCase() === "public") {
return 1;
}
if (spec1.type.toLowerCase() === "private" && spec2.type.toLowerCase() === "isolated") {
return -1;
}
// Isolated is the only remaining case, and they always come last.
return 1;
}
export interface OverlappingSubnet {
cidrBlock: string;
subnetName: string;
}
export function getOverlappingSubnets(specs: OverlappingSubnet[]): OverlappingSubnet[] {
const ipAddress = require("ip-address");
const overlaps = (spec1: OverlappingSubnet, spec2: OverlappingSubnet) => {
const ip1 = new ipAddress.Address4(spec1.cidrBlock);
const ip2 = new ipAddress.Address4(spec2.cidrBlock);
return ip1.isInSubnet(ip2) || ip2.isInSubnet(ip1);
};
return specs.filter((x) => specs.filter((y) => x !== y && overlaps(x, y)).length > 0);
}
export function validateSubnets(
specs: SubnetSpec[],
getOverlappingSubnets: (specs: OverlappingSubnet[]) => OverlappingSubnet[],
) {
const overlappingSubnets = getOverlappingSubnets(specs);
if (overlappingSubnets.length > 0) {
let msg =
"The following subnets overlap with at least one other subnet. Make the CIDR for the VPC larger, reduce the size of the subnets per AZ, or use less Availability Zones:\n\n";
for (let i = 0; i < overlappingSubnets.length; i++) {
msg += `${i + 1}. ${overlappingSubnets[i].subnetName}: ${overlappingSubnets[i].cidrBlock}\n`;
}
throw new Error(msg);
}
}
export function validateNoGaps(vpcCidr: string, subnetSpecs: SubnetSpec[]) {
const vpcNetmask = new Netmask(vpcCidr);
const gaps: string[] = [];
let current: SubnetSpec | undefined;
for (const spec of subnetSpecs) {
const prev = current;
current = spec;
const currentNetmask = new Netmask(current.cidrBlock);
if (prev === undefined) {
// Check the first subnet against the VPC CIDR
if (currentNetmask.base !== vpcNetmask.base) {
gaps.push(
`${spec.subnetName} (${spec.cidrBlock}) does not start at the beginning of the VPC (${vpcCidr})`,
);
}
continue;
}
const prevNetmask = new Netmask(prev.cidrBlock);
const expectedNext = prevNetmask.next();
if (currentNetmask.base !== expectedNext.base) {
gaps.push(
`${prev.subnetName} (${prev.cidrBlock}) <=> ${spec.subnetName} (${spec.cidrBlock})`,
);
}
}
const lastBlockNetmask = new Netmask(current!.cidrBlock);
if (lastBlockNetmask.last !== vpcNetmask.last) {
gaps.push(
`${current!.subnetName} (ending ${lastBlockNetmask.last}) ends before VPC ends (at ${
vpcNetmask.last
}})`,
);
}
if (gaps.length === 0) {
return;
}
throw new Error(
`There are gaps in the subnet ranges. Please fix the following gaps: ${gaps.join(", ")}`,
);
}