-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
vpc.ts
2751 lines (2393 loc) · 85.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
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Construct, Dependable, DependencyGroup, IConstruct, IDependable, Node } from 'constructs';
import { ClientVpnEndpoint, ClientVpnEndpointOptions } from './client-vpn-endpoint';
import {
CfnEIP, CfnEgressOnlyInternetGateway, CfnInternetGateway, CfnNatGateway, CfnRoute, CfnRouteTable, CfnSubnet,
CfnSubnetRouteTableAssociation, CfnVPC, CfnVPCCidrBlock, CfnVPCGatewayAttachment, CfnVPNGatewayRoutePropagation,
} from './ec2.generated';
import { AllocatedSubnet, IIpAddresses, RequestedSubnet, IpAddresses, IIpv6Addresses, Ipv6Addresses } from './ip-addresses';
import { NatProvider } from './nat';
import { INetworkAcl, NetworkAcl, SubnetNetworkAclAssociation } from './network-acl';
import { SubnetFilter } from './subnet';
import { allRouteTableIds, defaultSubnetName, flatten, ImportSubnetGroup, subnetGroupNameFromConstructId, subnetId } from './util';
import { GatewayVpcEndpoint, GatewayVpcEndpointAwsService, GatewayVpcEndpointOptions, InterfaceVpcEndpoint, InterfaceVpcEndpointOptions } from './vpc-endpoint';
import { FlowLog, FlowLogOptions, FlowLogResourceType } from './vpc-flow-logs';
import { VpcLookupOptions } from './vpc-lookup';
import { EnableVpnGatewayOptions, VpnConnection, VpnConnectionOptions, VpnConnectionType, VpnGateway } from './vpn';
import * as cxschema from '../../cloud-assembly-schema';
import {
Arn, Annotations, ContextProvider,
IResource, Fn, Lazy, Resource, Stack, Token, Tags, Names, CustomResource, FeatureFlags,
} from '../../core';
import { RestrictDefaultSgProvider } from '../../custom-resource-handlers/dist/aws-ec2/restrict-default-sg-provider.generated';
import * as cxapi from '../../cx-api';
import { EC2_RESTRICT_DEFAULT_SECURITY_GROUP } from '../../cx-api';
const VPC_SUBNET_SYMBOL = Symbol.for('@aws-cdk/aws-ec2.VpcSubnet');
const FAKE_AZ_NAME = 'fake-az';
export interface ISubnet extends IResource {
/**
* The Availability Zone the subnet is located in
*/
readonly availabilityZone: string;
/**
* The subnetId for this particular subnet
* @attribute
*/
readonly subnetId: string;
/**
* Dependable that can be depended upon to force internet connectivity established on the VPC
*/
readonly internetConnectivityEstablished: IDependable;
/**
* The IPv4 CIDR block for this subnet
*/
readonly ipv4CidrBlock: string;
/**
* The route table for this subnet
*/
readonly routeTable: IRouteTable;
/**
* Associate a Network ACL with this subnet
*
* @param acl The Network ACL to associate
*/
associateNetworkAcl(id: string, acl: INetworkAcl): void;
}
/**
* An abstract route table
*/
export interface IRouteTable {
/**
* Route table ID
*/
readonly routeTableId: string;
}
export interface IVpc extends IResource {
/**
* Identifier for this VPC
* @attribute
*/
readonly vpcId: string;
/**
* ARN for this VPC
* @attribute
*/
readonly vpcArn: string;
/**
* CIDR range for this VPC
*
* @attribute
*/
readonly vpcCidrBlock: string;
/**
* List of public subnets in this VPC
*/
readonly publicSubnets: ISubnet[];
/**
* List of private subnets in this VPC
*/
readonly privateSubnets: ISubnet[];
/**
* List of isolated subnets in this VPC
*/
readonly isolatedSubnets: ISubnet[];
/**
* AZs for this VPC
*/
readonly availabilityZones: string[];
/**
* Identifier for the VPN gateway
*/
readonly vpnGatewayId?: string;
/**
* Dependable that can be depended upon to force internet connectivity established on the VPC
*/
readonly internetConnectivityEstablished: IDependable;
/**
* Return information on the subnets appropriate for the given selection strategy
*
* Requires that at least one subnet is matched, throws a descriptive
* error message otherwise.
*/
selectSubnets(selection?: SubnetSelection): SelectedSubnets;
/**
* Adds a VPN Gateway to this VPC
*/
enableVpnGateway(options: EnableVpnGatewayOptions): void;
/**
* Adds a new VPN connection to this VPC
*/
addVpnConnection(id: string, options: VpnConnectionOptions): VpnConnection;
/**
* Adds a new client VPN endpoint to this VPC
*/
addClientVpnEndpoint(id: string, options: ClientVpnEndpointOptions): ClientVpnEndpoint;
/**
* Adds a new gateway endpoint to this VPC
*/
addGatewayEndpoint(id: string, options: GatewayVpcEndpointOptions): GatewayVpcEndpoint
/**
* Adds a new interface endpoint to this VPC
*/
addInterfaceEndpoint(id: string, options: InterfaceVpcEndpointOptions): InterfaceVpcEndpoint
/**
* Adds a new Flow Log to this VPC
*/
addFlowLog(id: string, options?: FlowLogOptions): FlowLog
}
/**
* The types of IP addresses provisioned in the VPC.
*/
export enum IpProtocol {
/**
* The vpc will be configured with only IPv4 addresses.
*
* This is the default protocol if unset.
*/
IPV4_ONLY = 'Ipv4_Only',
/**
* The vpc will have both IPv4 and IPv6 addresses.
*
* Unless specified, public IPv4 addresses will not be auto assigned,
* an egress only internet gateway (EIGW) will be created and configured,
* and NATs and internet gateways (IGW) will be configured with IPv6 addresses.
*/
DUAL_STACK = 'Dual_Stack',
}
/**
* The type of Subnet
*/
export enum SubnetType {
/**
* Isolated Subnets do not route traffic to the Internet (in this VPC),
* and as such, do not require NAT gateways.
*
* Isolated subnets can only connect to or be connected to from other
* instances in the same VPC. A default VPC configuration will not include
* isolated subnets.
*
* This can be good for subnets with RDS or Elasticache instances,
* or which route Internet traffic through a peer VPC.
*/
PRIVATE_ISOLATED = 'Isolated',
/**
* Isolated Subnets do not route traffic to the Internet (in this VPC),
* and as such, do not require NAT gateways.
*
* Isolated subnets can only connect to or be connected to from other
* instances in the same VPC. A default VPC configuration will not include
* isolated subnets.
*
* This can be good for subnets with RDS or Elasticache instances,
* or which route Internet traffic through a peer VPC.
*
* @deprecated use `SubnetType.PRIVATE_ISOLATED`
*/
ISOLATED = 'Deprecated_Isolated',
/**
* Subnet that routes to the internet, but not vice versa.
*
* Instances in a private subnet can connect to the Internet, but will not
* allow connections to be initiated from the Internet. Egress to the internet will
* need to be provided.
* NAT Gateway(s) are the default solution to providing this subnet type the ability to route Internet traffic.
* If a NAT Gateway is not required or desired, set `natGateways:0` or use
* `SubnetType.PRIVATE_ISOLATED` instead.
*
* By default, a NAT gateway is created in every public subnet for maximum availability.
* Be aware that you will be charged for NAT gateways.
*
* Normally a Private subnet will use a NAT gateway in the same AZ, but
* if `natGateways` is used to reduce the number of NAT gateways, a NAT
* gateway from another AZ will be used instead.
*/
PRIVATE_WITH_EGRESS = 'Private',
/**
* Subnet that routes to the internet (via a NAT gateway), but not vice versa.
*
* Instances in a private subnet can connect to the Internet, but will not
* allow connections to be initiated from the Internet. NAT Gateway(s) are
* required with this subnet type to route the Internet traffic through.
* If a NAT Gateway is not required or desired, use `SubnetType.PRIVATE_ISOLATED` instead.
*
* By default, a NAT gateway is created in every public subnet for maximum availability.
* Be aware that you will be charged for NAT gateways.
*
* Normally a Private subnet will use a NAT gateway in the same AZ, but
* if `natGateways` is used to reduce the number of NAT gateways, a NAT
* gateway from another AZ will be used instead.
* @deprecated use `PRIVATE_WITH_EGRESS`
*/
PRIVATE_WITH_NAT = 'Deprecated_Private_NAT',
/**
* Subnet that routes to the internet, but not vice versa.
*
* Instances in a private subnet can connect to the Internet, but will not
* allow connections to be initiated from the Internet. NAT Gateway(s) are
* required with this subnet type to route the Internet traffic through.
* If a NAT Gateway is not required or desired, use `SubnetType.PRIVATE_ISOLATED` instead.
*
* By default, a NAT gateway is created in every public subnet for maximum availability.
* Be aware that you will be charged for NAT gateways.
*
* Normally a Private subnet will use a NAT gateway in the same AZ, but
* if `natGateways` is used to reduce the number of NAT gateways, a NAT
* gateway from another AZ will be used instead.
*
* @deprecated use `PRIVATE_WITH_EGRESS`
*/
PRIVATE = 'Deprecated_Private',
/**
* Subnet connected to the Internet
*
* Instances in a Public subnet can connect to the Internet and can be
* connected to from the Internet as long as they are launched with public
* IPs (controlled on the AutoScalingGroup or other constructs that launch
* instances).
*
* Public subnets route outbound traffic via an Internet Gateway.
*/
PUBLIC = 'Public'
}
/**
* Customize subnets that are selected for placement of ENIs
*
* Constructs that allow customization of VPC placement use parameters of this
* type to provide placement settings.
*
* By default, the instances are placed in the private subnets.
*/
export interface SubnetSelection {
/**
* Select all subnets of the given type
*
* At most one of `subnetType` and `subnetGroupName` can be supplied.
*
* @default SubnetType.PRIVATE_WITH_EGRESS (or ISOLATED or PUBLIC if there are no PRIVATE_WITH_EGRESS subnets)
*/
readonly subnetType?: SubnetType;
/**
* Select subnets only in the given AZs.
*
* @default no filtering on AZs is done
*/
readonly availabilityZones?: string[];
/**
* Select the subnet group with the given name
*
* Select the subnet group with the given name. This only needs
* to be used if you have multiple subnet groups of the same type
* and you need to distinguish between them. Otherwise, prefer
* `subnetType`.
*
* This field does not select individual subnets, it selects all subnets that
* share the given subnet group name. This is the name supplied in
* `subnetConfiguration`.
*
* At most one of `subnetType` and `subnetGroupName` can be supplied.
*
* @default - Selection by type instead of by name
*/
readonly subnetGroupName?: string;
/**
* Alias for `subnetGroupName`
*
* Select the subnet group with the given name. This only needs
* to be used if you have multiple subnet groups of the same type
* and you need to distinguish between them.
*
* @deprecated Use `subnetGroupName` instead
*/
readonly subnetName?: string;
/**
* If true, return at most one subnet per AZ
*
* @default false
*/
readonly onePerAz?: boolean;
/**
* List of provided subnet filters.
*
* @default - none
*/
readonly subnetFilters?: SubnetFilter[];
/**
* Explicitly select individual subnets
*
* Use this if you don't want to automatically use all subnets in
* a group, but have a need to control selection down to
* individual subnets.
*
* Cannot be specified together with `subnetType` or `subnetGroupName`.
*
* @default - Use all subnets in a selected group (all private subnets by default)
*/
readonly subnets?: ISubnet[]
}
/**
* Result of selecting a subset of subnets from a VPC
*/
export interface SelectedSubnets {
/**
* The subnet IDs
*/
readonly subnetIds: string[];
/**
* The respective AZs of each subnet
*/
readonly availabilityZones: string[];
/**
* Dependency representing internet connectivity for these subnets
*/
readonly internetConnectivityEstablished: IDependable;
/**
* Selected subnet objects
*/
readonly subnets: ISubnet[];
/**
* Whether any of the given subnets are from the VPC's public subnets.
*/
readonly hasPublic: boolean;
/**
* The subnet selection is not actually real yet
*
* If this value is true, don't validate anything about the subnets. The count
* or identities are not known yet, and the validation will most likely fail
* which will prevent a successful lookup.
*
* @default false
*/
readonly isPendingLookup?: boolean;
}
/**
* A new or imported VPC
*/
abstract class VpcBase extends Resource implements IVpc {
/**
* Identifier for this VPC
*/
public abstract readonly vpcId: string;
/**
* Arn of this VPC
*/
public abstract readonly vpcArn: string;
/**
* CIDR range for this VPC
*/
public abstract readonly vpcCidrBlock: string;
/**
* List of public subnets in this VPC
*/
public abstract readonly publicSubnets: ISubnet[];
/**
* List of private subnets in this VPC
*/
public abstract readonly privateSubnets: ISubnet[];
/**
* List of isolated subnets in this VPC
*/
public abstract readonly isolatedSubnets: ISubnet[];
/**
* AZs for this VPC
*/
public abstract readonly availabilityZones: string[];
/**
* Dependencies for internet connectivity
*/
public abstract readonly internetConnectivityEstablished: IDependable;
/**
* Dependencies for NAT connectivity
*
* @deprecated - This value is no longer used.
*/
protected readonly natDependencies = new Array<IConstruct>();
/**
* If this is set to true, don't error out on trying to select subnets
*/
protected incompleteSubnetDefinition: boolean = false;
/**
* Mutable private field for the vpnGatewayId
*
* @internal
*/
protected _vpnGatewayId?: string;
/**
* Returns IDs of selected subnets
*/
public selectSubnets(selection: SubnetSelection = {}): SelectedSubnets {
const subnets = this.selectSubnetObjects(selection);
const pubs = new Set(this.publicSubnets);
return {
subnetIds: subnets.map(s => s.subnetId),
get availabilityZones(): string[] { return subnets.map(s => s.availabilityZone); },
internetConnectivityEstablished: tap(new CompositeDependable(), d => subnets.forEach(s => d.add(s.internetConnectivityEstablished))),
subnets,
hasPublic: subnets.some(s => pubs.has(s)),
isPendingLookup: this.incompleteSubnetDefinition,
};
}
/**
* Adds a VPN Gateway to this VPC
*/
public enableVpnGateway(options: EnableVpnGatewayOptions): void {
if (this.vpnGatewayId) {
throw new Error('The VPN Gateway has already been enabled.');
}
const vpnGateway = new VpnGateway(this, 'VpnGateway', {
amazonSideAsn: options.amazonSideAsn,
type: VpnConnectionType.IPSEC_1,
});
this._vpnGatewayId = vpnGateway.gatewayId;
const attachment = new CfnVPCGatewayAttachment(this, 'VPCVPNGW', {
vpcId: this.vpcId,
vpnGatewayId: this._vpnGatewayId,
});
// Propagate routes on route tables associated with the right subnets
const vpnRoutePropagation = options.vpnRoutePropagation ?? [{}];
const routeTableIds = allRouteTableIds(flatten(vpnRoutePropagation.map(s => this.selectSubnets(s).subnets)));
if (routeTableIds.length === 0) {
Annotations.of(this).addError(`enableVpnGateway: no subnets matching selection: '${JSON.stringify(vpnRoutePropagation)}'. Select other subnets to add routes to.`);
}
const routePropagation = new CfnVPNGatewayRoutePropagation(this, 'RoutePropagation', {
routeTableIds,
vpnGatewayId: this._vpnGatewayId,
});
// The AWS::EC2::VPNGatewayRoutePropagation resource cannot use the VPN gateway
// until it has successfully attached to the VPC.
// See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gatewayrouteprop.html
routePropagation.node.addDependency(attachment);
}
/**
* Adds a new VPN connection to this VPC
*/
public addVpnConnection(id: string, options: VpnConnectionOptions): VpnConnection {
return new VpnConnection(this, id, {
vpc: this,
...options,
});
}
/**
* Adds a new client VPN endpoint to this VPC
*/
public addClientVpnEndpoint(id: string, options: ClientVpnEndpointOptions): ClientVpnEndpoint {
return new ClientVpnEndpoint(this, id, {
...options,
vpc: this,
});
}
/**
* Adds a new interface endpoint to this VPC
*/
public addInterfaceEndpoint(id: string, options: InterfaceVpcEndpointOptions): InterfaceVpcEndpoint {
return new InterfaceVpcEndpoint(this, id, {
vpc: this,
...options,
});
}
/**
* Adds a new gateway endpoint to this VPC
*/
public addGatewayEndpoint(id: string, options: GatewayVpcEndpointOptions): GatewayVpcEndpoint {
return new GatewayVpcEndpoint(this, id, {
vpc: this,
...options,
});
}
/**
* Adds a new flow log to this VPC
*/
public addFlowLog(id: string, options?: FlowLogOptions): FlowLog {
return new FlowLog(this, id, {
resourceType: FlowLogResourceType.fromVpc(this),
...options,
});
}
/**
* Returns the id of the VPN Gateway (if enabled)
*/
public get vpnGatewayId(): string | undefined {
return this._vpnGatewayId;
}
/**
* Return the subnets appropriate for the placement strategy
*/
protected selectSubnetObjects(selection: SubnetSelection = {}): ISubnet[] {
selection = this.reifySelectionDefaults(selection);
if (selection.subnets !== undefined) {
return selection.subnets;
}
let subnets;
if (selection.subnetGroupName !== undefined) { // Select by name
subnets = this.selectSubnetObjectsByName(selection.subnetGroupName);
} else { // Or specify by type
const type = selection.subnetType || SubnetType.PRIVATE_WITH_EGRESS;
subnets = this.selectSubnetObjectsByType(type);
}
// Apply all the filters
subnets = this.applySubnetFilters(subnets, selection.subnetFilters ?? []);
return subnets;
}
private applySubnetFilters(subnets: ISubnet[], filters: SubnetFilter[]): ISubnet[] {
let filtered = subnets;
// Apply each filter in sequence
for (const filter of filters) {
filtered = filter.selectSubnets(filtered);
}
return filtered;
}
private selectSubnetObjectsByName(groupName: string) {
const allSubnets = [...this.publicSubnets, ...this.privateSubnets, ...this.isolatedSubnets];
const subnets = allSubnets.filter(s => subnetGroupNameFromConstructId(s) === groupName);
if (subnets.length === 0 && !this.incompleteSubnetDefinition) {
const names = Array.from(new Set(allSubnets.map(subnetGroupNameFromConstructId)));
throw new Error(`There are no subnet groups with name '${groupName}' in this VPC. Available names: ${names}`);
}
return subnets;
}
private selectSubnetObjectsByType(subnetType: SubnetType) {
const allSubnets = {
[SubnetType.PRIVATE_ISOLATED]: this.isolatedSubnets,
[SubnetType.ISOLATED]: this.isolatedSubnets,
[SubnetType.PRIVATE_WITH_NAT]: this.privateSubnets,
[SubnetType.PRIVATE_WITH_EGRESS]: this.privateSubnets,
[SubnetType.PRIVATE]: this.privateSubnets,
[SubnetType.PUBLIC]: this.publicSubnets,
};
const subnets = allSubnets[subnetType];
// Force merge conflict here with https://github.com/aws/aws-cdk/pull/4089
// see ImportedVpc
if (subnets.length === 0 && !this.incompleteSubnetDefinition) {
const availableTypes = Object.entries(allSubnets).filter(([_, subs]) => subs.length > 0).map(([typeName, _]) => typeName);
throw new Error(`There are no '${subnetType}' subnet groups in this VPC. Available types: ${availableTypes}`);
}
return subnets;
}
/**
* Validate the fields in a SubnetSelection object, and reify defaults if necessary
*
* In case of default selection, select the first type of PRIVATE, ISOLATED,
* PUBLIC (in that order) that has any subnets.
*/
private reifySelectionDefaults(placement: SubnetSelection): SubnetSelection {
if (placement.subnetName !== undefined) {
if (placement.subnetGroupName !== undefined) {
throw new Error('Please use only \'subnetGroupName\' (\'subnetName\' is deprecated and has the same behavior)');
} else {
Annotations.of(this).addWarningV2('@aws-cdk/aws-ec2:subnetNameDeprecated', 'Usage of \'subnetName\' in SubnetSelection is deprecated, use \'subnetGroupName\' instead');
}
placement = { ...placement, subnetGroupName: placement.subnetName };
}
const exclusiveSelections: Array<keyof SubnetSelection> = ['subnets', 'subnetType', 'subnetGroupName'];
const providedSelections = exclusiveSelections.filter(key => placement[key] !== undefined);
if (providedSelections.length > 1) {
throw new Error(`Only one of '${providedSelections}' can be supplied to subnet selection.`);
}
if (placement.subnetType === undefined && placement.subnetGroupName === undefined && placement.subnets === undefined) {
// Return default subnet type based on subnets that actually exist
let subnetType = this.privateSubnets.length
? SubnetType.PRIVATE_WITH_EGRESS : this.isolatedSubnets.length ? SubnetType.PRIVATE_ISOLATED : SubnetType.PUBLIC;
placement = { ...placement, subnetType: subnetType };
}
// Establish which subnet filters are going to be used
let subnetFilters = placement.subnetFilters ?? [];
// Backwards compatibility with existing `availabilityZones` and `onePerAz` functionality
if (placement.availabilityZones !== undefined) { // Filter by AZs, if specified
subnetFilters.push(SubnetFilter.availabilityZones(placement.availabilityZones));
}
if (!!placement.onePerAz) { // Ensure one per AZ if specified
subnetFilters.push(SubnetFilter.onePerAz());
}
// Overwrite the provided placement filters and remove the availabilityZones and onePerAz properties
placement = { ...placement, subnetFilters: subnetFilters, availabilityZones: undefined, onePerAz: undefined };
const { availabilityZones, onePerAz, ...rest } = placement;
return rest;
}
}
/**
* Properties that reference an external Vpc
*/
export interface VpcAttributes {
/**
* VPC's identifier
*/
readonly vpcId: string;
/**
* VPC's CIDR range
*
* @default - Retrieving the CIDR from the VPC will fail
*/
readonly vpcCidrBlock?: string;
/**
* List of availability zones for the subnets in this VPC.
*/
readonly availabilityZones: string[];
/**
* List of public subnet IDs
*
* Must be undefined or match the availability zones in length and order.
*
* @default - The VPC does not have any public subnets
*/
readonly publicSubnetIds?: string[];
/**
* List of names for the public subnets
*
* Must be undefined or have a name for every public subnet group.
*
* @default - All public subnets will have the name `Public`
*/
readonly publicSubnetNames?: string[];
/**
* List of IDs of route tables for the public subnets.
*
* Must be undefined or have a name for every public subnet group.
*
* @default - Retrieving the route table ID of any public subnet will fail
*/
readonly publicSubnetRouteTableIds?: string[];
/**
* List of IPv4 CIDR blocks for the public subnets.
*
* Must be undefined or have an entry for every public subnet group.
*
* @default - Retrieving the IPv4 CIDR block of any public subnet will fail
*/
readonly publicSubnetIpv4CidrBlocks?: string[];
/**
* List of private subnet IDs
*
* Must be undefined or match the availability zones in length and order.
*
* @default - The VPC does not have any private subnets
*/
readonly privateSubnetIds?: string[];
/**
* List of names for the private subnets
*
* Must be undefined or have a name for every private subnet group.
*
* @default - All private subnets will have the name `Private`
*/
readonly privateSubnetNames?: string[];
/**
* List of IDs of route tables for the private subnets.
*
* Must be undefined or have a name for every private subnet group.
*
* @default - Retrieving the route table ID of any private subnet will fail
*/
readonly privateSubnetRouteTableIds?: string[];
/**
* List of IPv4 CIDR blocks for the private subnets.
*
* Must be undefined or have an entry for every private subnet group.
*
* @default - Retrieving the IPv4 CIDR block of any private subnet will fail
*/
readonly privateSubnetIpv4CidrBlocks?: string[];
/**
* List of isolated subnet IDs
*
* Must be undefined or match the availability zones in length and order.
*
* @default - The VPC does not have any isolated subnets
*/
readonly isolatedSubnetIds?: string[];
/**
* List of names for the isolated subnets
*
* Must be undefined or have a name for every isolated subnet group.
*
* @default - All isolated subnets will have the name `Isolated`
*/
readonly isolatedSubnetNames?: string[];
/**
* List of IDs of route tables for the isolated subnets.
*
* Must be undefined or have a name for every isolated subnet group.
*
* @default - Retrieving the route table ID of any isolated subnet will fail
*/
readonly isolatedSubnetRouteTableIds?: string[];
/**
* List of IPv4 CIDR blocks for the isolated subnets.
*
* Must be undefined or have an entry for every isolated subnet group.
*
* @default - Retrieving the IPv4 CIDR block of any isolated subnet will fail
*/
readonly isolatedSubnetIpv4CidrBlocks?: string[];
/**
* VPN gateway's identifier
*/
readonly vpnGatewayId?: string;
/**
* The region the VPC is in
*
* @default - The region of the stack where the VPC belongs to
*/
readonly region?: string;
}
export interface SubnetAttributes {
/**
* The Availability Zone the subnet is located in
*
* @default - No AZ information, cannot use AZ selection features
*/
readonly availabilityZone?: string;
/**
* The IPv4 CIDR block associated with the subnet
*
* @default - No CIDR information, cannot use CIDR filter features
*/
readonly ipv4CidrBlock?: string;
/**
* The ID of the route table for this particular subnet
*
* @default - No route table information, cannot create VPC endpoints
*/
readonly routeTableId?: string;
/**
* The subnetId for this particular subnet
*/
readonly subnetId: string;
}
/**
* Name tag constant
*/
const NAME_TAG: string = 'Name';
/**
* Configuration for Vpc
*/
export interface VpcProps {
/**
* The protocol of the vpc.
*
* Options are IPv4 only or dual stack.
*
* @default IpProtocol.IPV4_ONLY
*/
readonly ipProtocol?: IpProtocol;
/**
* The Provider to use to allocate IPv4 Space to your VPC.
*
* Options include static allocation or from a pool.
*
* Note this is specific to IPv4 addresses.
*
* @default ec2.IpAddresses.cidr
*/
readonly ipAddresses?: IIpAddresses;
/**
* The CIDR range to use for the VPC, e.g. '10.0.0.0/16'.
*
* Should be a minimum of /28 and maximum size of /16. The range will be
* split across all subnets per Availability Zone.
*
* @default Vpc.DEFAULT_CIDR_RANGE
*
* @deprecated Use ipAddresses instead
*/
readonly cidr?: string;
/**
* Indicates whether the instances launched in the VPC get public DNS hostnames.
*
* If this attribute is true, instances in the VPC get public DNS hostnames,
* but only if the enableDnsSupport attribute is also set to true.
*
* @default true
*/
readonly enableDnsHostnames?: boolean;
/**
* Indicates whether the DNS resolution is supported for the VPC.
*
* If this attribute is false, the Amazon-provided DNS server in the VPC that
* resolves public DNS hostnames to IP addresses is not enabled. If this
* attribute is true, queries to the Amazon provided DNS server at the
* 169.254.169.253 IP address, or the reserved IP address at the base of the
* VPC IPv4 network range plus two will succeed.
*
* @default true
*/
readonly enableDnsSupport?: boolean;
/**
* The default tenancy of instances launched into the VPC.
*
* By setting this to dedicated tenancy, instances will be launched on
* hardware dedicated to a single AWS customer, unless specifically specified
* at instance launch time. Please note, not all instance types are usable
* with Dedicated tenancy.
*
* @default DefaultInstanceTenancy.Default (shared) tenancy
*/
readonly defaultInstanceTenancy?: DefaultInstanceTenancy;
/**
* Define the maximum number of AZs to use in this region
*
* If the region has more AZs than you want to use (for example, because of
* EIP limits), pick a lower number here. The AZs will be sorted and picked
* from the start of the list.
*
* If you pick a higher number than the number of AZs in the region, all AZs
* in the region will be selected. To use "all AZs" available to your
* account, use a high number (such as 99).
*
* Be aware that environment-agnostic stacks will be created with access to
* only 2 AZs, so to use more than 2 AZs, be sure to specify the account and
* region on your stack.
*
* Specify this option only if you do not specify `availabilityZones`.
*
* @default 3
*/
readonly maxAzs?: number;
/**
* Define the number of AZs to reserve.
*
* When specified, the IP space is reserved for the azs but no actual
* resources are provisioned.
*
* @default 0
*/
readonly reservedAzs?: number;
/**
* Availability zones this VPC spans.
*
* Specify this option only if you do not specify `maxAzs`.
*
* @default - a subset of AZs of the stack
*/
readonly availabilityZones?: string[];
/**
* The number of NAT Gateways/Instances to create.
*
* The type of NAT gateway or instance will be determined by the
* `natGatewayProvider` parameter.
*
* You can set this number lower than the number of Availability Zones in your
* VPC in order to save on NAT cost. Be aware you may be charged for
* cross-AZ data traffic instead.
*
* @default - One NAT gateway/instance per Availability Zone
*/