-
Notifications
You must be signed in to change notification settings - Fork 4k
/
cluster.ts
1856 lines (1608 loc) · 61.5 KB
/
cluster.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 * as fs from 'fs';
import * as path from 'path';
import * as autoscaling from '@aws-cdk/aws-autoscaling';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as iam from '@aws-cdk/aws-iam';
import * as kms from '@aws-cdk/aws-kms';
import * as lambda from '@aws-cdk/aws-lambda';
import * as ssm from '@aws-cdk/aws-ssm';
import { Annotations, CfnOutput, CfnResource, IResource, Resource, Stack, Tags, Token, Duration } from '@aws-cdk/core';
import { Construct, Node } from 'constructs';
import * as YAML from 'yaml';
import { AwsAuth } from './aws-auth';
import { ClusterResource, clusterArnComponents } from './cluster-resource';
import { FargateProfile, FargateProfileOptions } from './fargate-profile';
import { HelmChart, HelmChartOptions } from './helm-chart';
import { INSTANCE_TYPES } from './instance-types';
import { KubernetesManifest } from './k8s-manifest';
import { KubernetesObjectValue } from './k8s-object-value';
import { KubernetesPatch } from './k8s-patch';
import { KubectlProvider } from './kubectl-provider';
import { Nodegroup, NodegroupOptions } from './managed-nodegroup';
import { OpenIdConnectProvider } from './oidc-provider';
import { BottleRocketImage } from './private/bottlerocket';
import { ServiceAccount, ServiceAccountOptions } from './service-account';
import { LifecycleLabel, renderAmazonLinuxUserData, renderBottlerocketUserData } from './user-data';
// v2 - keep this import as a separate section to reduce merge conflict when forward merging with the v2 branch.
// eslint-disable-next-line
import { Construct as CoreConstruct } from '@aws-cdk/core';
// defaults are based on https://eksctl.io
const DEFAULT_CAPACITY_COUNT = 2;
const DEFAULT_CAPACITY_TYPE = ec2.InstanceType.of(ec2.InstanceClass.M5, ec2.InstanceSize.LARGE);
/**
* An EKS cluster
*/
export interface ICluster extends IResource, ec2.IConnectable {
/**
* The VPC in which this Cluster was created
*/
readonly vpc: ec2.IVpc;
/**
* The physical name of the Cluster
* @attribute
*/
readonly clusterName: string;
/**
* The unique ARN assigned to the service by AWS
* in the form of arn:aws:eks:
* @attribute
*/
readonly clusterArn: string;
/**
* The API Server endpoint URL
* @attribute
*/
readonly clusterEndpoint: string;
/**
* The certificate-authority-data for your cluster.
* @attribute
*/
readonly clusterCertificateAuthorityData: string;
/**
* The cluster security group that was created by Amazon EKS for the cluster.
* @attribute
*/
readonly clusterSecurityGroupId: string;
/**
* Amazon Resource Name (ARN) or alias of the customer master key (CMK).
* @attribute
*/
readonly clusterEncryptionConfigKeyArn: string;
/**
* The Open ID Connect Provider of the cluster used to configure Service Accounts.
*/
readonly openIdConnectProvider: iam.IOpenIdConnectProvider;
/**
* An IAM role that can perform kubectl operations against this cluster.
*
* The role should be mapped to the `system:masters` Kubernetes RBAC role.
*/
readonly kubectlRole?: iam.IRole;
/**
* Custom environment variables when running `kubectl` against this cluster.
* @default - no additional environment variables
*/
readonly kubectlEnvironment?: { [key: string]: string };
/**
* A security group to use for `kubectl` execution.
*
* @default - If not specified, the k8s endpoint is expected to be accessible
* publicly.
*/
readonly kubectlSecurityGroup?: ec2.ISecurityGroup;
/**
* Subnets to host the `kubectl` compute resources.
*
* @default - If not specified, the k8s endpoint is expected to be accessible
* publicly.
*/
readonly kubectlPrivateSubnets?: ec2.ISubnet[];
/**
* An AWS Lambda layer that includes `kubectl`, `helm` and the `aws` CLI.
*
* If not defined, a default layer will be used.
*/
readonly kubectlLayer?: lambda.ILayerVersion;
/**
* Creates a new service account with corresponding IAM Role (IRSA).
*
* @param id logical id of service account
* @param options service account options
*/
addServiceAccount(id: string, options?: ServiceAccountOptions): ServiceAccount;
/**
* Defines a Kubernetes resource in this cluster.
*
* The manifest will be applied/deleted using kubectl as needed.
*
* @param id logical id of this manifest
* @param manifest a list of Kubernetes resource specifications
* @returns a `KubernetesManifest` object.
*/
addManifest(id: string, ...manifest: Record<string, any>[]): KubernetesManifest;
/**
* Defines a Helm chart in this cluster.
*
* @param id logical id of this chart.
* @param options options of this chart.
* @returns a `HelmChart` construct
*/
addHelmChart(id: string, options: HelmChartOptions): HelmChart;
/**
* Defines a CDK8s chart in this cluster.
*
* @param id logical id of this chart.
* @param chart the cdk8s chart.
* @returns a `KubernetesManifest` construct representing the chart.
*/
addCdk8sChart(id: string, chart: Construct): KubernetesManifest;
}
/**
* Attributes for EKS clusters.
*/
export interface ClusterAttributes {
/**
* The VPC in which this Cluster was created
* @default - if not specified `cluster.vpc` will throw an error
*/
readonly vpc?: ec2.IVpc;
/**
* The physical name of the Cluster
*/
readonly clusterName: string;
/**
* The API Server endpoint URL
* @default - if not specified `cluster.clusterEndpoint` will throw an error.
*/
readonly clusterEndpoint?: string;
/**
* The certificate-authority-data for your cluster.
* @default - if not specified `cluster.clusterCertificateAuthorityData` will
* throw an error
*/
readonly clusterCertificateAuthorityData?: string;
/**
* The cluster security group that was created by Amazon EKS for the cluster.
* @default - if not specified `cluster.clusterSecurityGroupId` will throw an
* error
*/
readonly clusterSecurityGroupId?: string;
/**
* Amazon Resource Name (ARN) or alias of the customer master key (CMK).
* @default - if not specified `cluster.clusterEncryptionConfigKeyArn` will
* throw an error
*/
readonly clusterEncryptionConfigKeyArn?: string;
/**
* Additional security groups associated with this cluster.
* @default - if not specified, no additional security groups will be
* considered in `cluster.connections`.
*/
readonly securityGroupIds?: string[];
/**
* An IAM role with cluster administrator and "system:masters" permissions.
* @default - if not specified, it not be possible to issue `kubectl` commands
* against an imported cluster.
*/
readonly kubectlRoleArn?: string;
/**
* Environment variables to use when running `kubectl` against this cluster.
* @default - no additional variables
*/
readonly kubectlEnvironment?: { [name: string]: string };
/**
* A security group to use for `kubectl` execution. If not specified, the k8s
* endpoint is expected to be accessible publicly.
* @default - k8s endpoint is expected to be accessible publicly
*/
readonly kubectlSecurityGroupId?: string;
/**
* Subnets to host the `kubectl` compute resources. If not specified, the k8s
* endpoint is expected to be accessible publicly.
* @default - k8s endpoint is expected to be accessible publicly
*/
readonly kubectlPrivateSubnetIds?: string[];
/**
* An Open ID Connect provider for this cluster that can be used to configure service accounts.
* You can either import an existing provider using `iam.OpenIdConnectProvider.fromProviderArn`,
* or create a new provider using `new eks.OpenIdConnectProvider`
* @default - if not specified `cluster.openIdConnectProvider` and `cluster.addServiceAccount` will throw an error.
*/
readonly openIdConnectProvider?: iam.IOpenIdConnectProvider;
/**
* An AWS Lambda Layer which includes `kubectl`, Helm and the AWS CLI.
*
* By default, the provider will use the layer included in the
* "aws-lambda-layer-kubectl" SAR application which is available in all
* commercial regions.
*
* To deploy the layer locally, visit
* https://github.com/aws-samples/aws-lambda-layer-kubectl/blob/master/cdk/README.md
* for instructions on how to prepare the .zip file and then define it in your
* app as follows:
*
* ```ts
* const layer = new lambda.LayerVersion(this, 'kubectl-layer', {
* code: lambda.Code.fromAsset(`${__dirname}/layer.zip`)),
* compatibleRuntimes: [lambda.Runtime.PROVIDED]
* });
*
* Or you can use the standard layer like this (with options
* to customize the version and SAR application ID):
*
* ```ts
* const layer = new eks.KubectlLayer(this, 'KubectlLayer');
* ```
*
* @default - the layer provided by the `aws-lambda-layer-kubectl` SAR app.
* @see https://github.com/aws-samples/aws-lambda-layer-kubectl
*/
readonly kubectlLayer?: lambda.ILayerVersion;
}
/**
* Options for configuring an EKS cluster.
*/
export interface CommonClusterOptions {
/**
* The VPC in which to create the Cluster.
*
* @default - a VPC with default configuration will be created and can be accessed through `cluster.vpc`.
*/
readonly vpc?: ec2.IVpc;
/**
* Where to place EKS Control Plane ENIs
*
* If you want to create public load balancers, this must include public subnets.
*
* For example, to only select private subnets, supply the following:
*
* ```ts
* vpcSubnets: [
* { subnetType: ec2.SubnetType.Private }
* ]
* ```
*
* @default - All public and private subnets
*/
readonly vpcSubnets?: ec2.SubnetSelection[];
/**
* Role that provides permissions for the Kubernetes control plane to make calls to AWS API operations on your behalf.
*
* @default - A role is automatically created for you
*/
readonly role?: iam.IRole;
/**
* Name for the cluster.
*
* @default - Automatically generated name
*/
readonly clusterName?: string;
/**
* Security Group to use for Control Plane ENIs
*
* @default - A security group is automatically created
*/
readonly securityGroup?: ec2.ISecurityGroup;
/**
* The Kubernetes version to run in the cluster
*/
readonly version: KubernetesVersion;
/**
* Determines whether a CloudFormation output with the name of the cluster
* will be synthesized.
*
* @default false
*/
readonly outputClusterName?: boolean;
/**
* Determines whether a CloudFormation output with the `aws eks
* update-kubeconfig` command will be synthesized. This command will include
* the cluster name and, if applicable, the ARN of the masters IAM role.
*
* @default true
*/
readonly outputConfigCommand?: boolean;
}
/**
* Options for EKS clusters.
*/
export interface ClusterOptions extends CommonClusterOptions {
/**
* An IAM role that will be added to the `system:masters` Kubernetes RBAC
* group.
*
* @see https://kubernetes.io/docs/reference/access-authn-authz/rbac/#default-roles-and-role-bindings
*
* @default - a role that assumable by anyone with permissions in the same
* account will automatically be defined
*/
readonly mastersRole?: iam.IRole;
/**
* Controls the "eks.amazonaws.com/compute-type" annotation in the CoreDNS
* configuration on your cluster to determine which compute type to use
* for CoreDNS.
*
* @default CoreDnsComputeType.EC2 (for `FargateCluster` the default is FARGATE)
*/
readonly coreDnsComputeType?: CoreDnsComputeType;
/**
* Determines whether a CloudFormation output with the ARN of the "masters"
* IAM role will be synthesized (if `mastersRole` is specified).
*
* @default false
*/
readonly outputMastersRoleArn?: boolean;
/**
* Configure access to the Kubernetes API server endpoint..
*
* @see https://docs.aws.amazon.com/eks/latest/userguide/cluster-endpoint.html
*
* @default EndpointAccess.PUBLIC_AND_PRIVATE
*/
readonly endpointAccess?: EndpointAccess;
/**
* Environment variables for the kubectl execution. Only relevant for kubectl enabled clusters.
*
* @default - No environment variables.
*/
readonly kubectlEnvironment?: { [key: string]: string };
/**
* An AWS Lambda Layer which includes `kubectl`, Helm and the AWS CLI.
*
* By default, the provider will use the layer included in the
* "aws-lambda-layer-kubectl" SAR application which is available in all
* commercial regions.
*
* To deploy the layer locally, visit
* https://github.com/aws-samples/aws-lambda-layer-kubectl/blob/master/cdk/README.md
* for instructions on how to prepare the .zip file and then define it in your
* app as follows:
*
* ```ts
* const layer = new lambda.LayerVersion(this, 'kubectl-layer', {
* code: lambda.Code.fromAsset(`${__dirname}/layer.zip`)),
* compatibleRuntimes: [lambda.Runtime.PROVIDED]
* })
* ```
*
* @default - the layer provided by the `aws-lambda-layer-kubectl` SAR app.
* @see https://github.com/aws-samples/aws-lambda-layer-kubectl
*/
readonly kubectlLayer?: lambda.ILayerVersion;
}
/**
* Group access configuration together.
*/
interface EndpointAccessConfig {
/**
* Indicates if private access is enabled.
*/
readonly privateAccess: boolean;
/**
* Indicates if public access is enabled.
*/
readonly publicAccess: boolean;
/**
* Public access is allowed only from these CIDR blocks.
* An empty array means access is open to any address.
*
* @default - No restrictions.
*/
readonly publicCidrs?: string[];
}
/**
* Endpoint access characteristics.
*/
export class EndpointAccess {
/**
* The cluster endpoint is accessible from outside of your VPC.
* Worker node traffic will leave your VPC to connect to the endpoint.
*
* By default, the endpoint is exposed to all adresses. You can optionally limit the CIDR blocks that can access the public endpoint using the `PUBLIC.onlyFrom` method.
* If you limit access to specific CIDR blocks, you must ensure that the CIDR blocks that you
* specify include the addresses that worker nodes and Fargate pods (if you use them)
* access the public endpoint from.
*
* @param cidr The CIDR blocks.
*/
public static readonly PUBLIC = new EndpointAccess({ privateAccess: false, publicAccess: true });
/**
* The cluster endpoint is only accessible through your VPC.
* Worker node traffic to the endpoint will stay within your VPC.
*/
public static readonly PRIVATE = new EndpointAccess({ privateAccess: true, publicAccess: false });
/**
* The cluster endpoint is accessible from outside of your VPC.
* Worker node traffic to the endpoint will stay within your VPC.
*
* By default, the endpoint is exposed to all adresses. You can optionally limit the CIDR blocks that can access the public endpoint using the `PUBLIC_AND_PRIVATE.onlyFrom` method.
* If you limit access to specific CIDR blocks, you must ensure that the CIDR blocks that you
* specify include the addresses that worker nodes and Fargate pods (if you use them)
* access the public endpoint from.
*
* @param cidr The CIDR blocks.
*/
public static readonly PUBLIC_AND_PRIVATE = new EndpointAccess({ privateAccess: true, publicAccess: true });
private constructor(
/**
* Configuration properties.
*
* @internal
*/
public readonly _config: EndpointAccessConfig) {
if (!_config.publicAccess && _config.publicCidrs && _config.publicCidrs.length > 0) {
throw new Error('CIDR blocks can only be configured when public access is enabled');
}
}
/**
* Restrict public access to specific CIDR blocks.
* If public access is disabled, this method will result in an error.
*
* @param cidr CIDR blocks.
*/
public onlyFrom(...cidr: string[]) {
if (!this._config.privateAccess) {
// when private access is disabled, we can't restric public
// access since it will render the kubectl provider unusable.
throw new Error('Cannot restric public access to endpoint when private access is disabled. Use PUBLIC_AND_PRIVATE.onlyFrom() instead.');
}
return new EndpointAccess({
...this._config,
// override CIDR
publicCidrs: cidr,
});
}
}
/**
* Common configuration props for EKS clusters.
*/
export interface ClusterProps extends ClusterOptions {
/**
* NOT SUPPORTED: We no longer allow disabling kubectl-support. Setting this
* option to `false` will throw an error.
*
* To temporary allow you to retain existing clusters created with
* `kubectlEnabled: false`, you can use `eks.LegacyCluster` class, which is a
* drop-in replacement for `eks.Cluster` with `kubectlEnabled: false`.
*
* Bear in mind that this is a temporary workaround. We have plans to remove
* `eks.LegacyCluster`. If you have a use case for using `eks.LegacyCluster`,
* please add a comment here https://github.com/aws/aws-cdk/issues/9332 and
* let us know so we can make sure to continue to support your use case with
* `eks.Cluster`. This issue also includes additional context into why this
* class is being removed.
*
* @deprecated `eks.LegacyCluster` is __temporarily__ provided as a drop-in
* replacement until you are able to migrate to `eks.Cluster`.
*
* @see https://github.com/aws/aws-cdk/issues/9332
* @default true
*/
readonly kubectlEnabled?: boolean;
/**
* Number of instances to allocate as an initial capacity for this cluster.
* Instance type can be configured through `defaultCapacityInstanceType`,
* which defaults to `m5.large`.
*
* Use `cluster.addAutoScalingGroupCapacity` to add additional customized capacity. Set this
* to `0` is you wish to avoid the initial capacity allocation.
*
* @default 2
*/
readonly defaultCapacity?: number;
/**
* The instance type to use for the default capacity. This will only be taken
* into account if `defaultCapacity` is > 0.
*
* @default m5.large
*/
readonly defaultCapacityInstance?: ec2.InstanceType;
/**
* The default capacity type for the cluster.
*
* @default NODEGROUP
*/
readonly defaultCapacityType?: DefaultCapacityType;
/**
* KMS secret for envelope encryption for Kubernetes secrets.
*
* @default - By default, Kubernetes stores all secret object data within etcd and
* all etcd volumes used by Amazon EKS are encrypted at the disk-level
* using AWS-Managed encryption keys.
*/
readonly secretsEncryptionKey?: kms.IKey;
}
/**
* Kubernetes cluster version
*/
export class KubernetesVersion {
/**
* Kubernetes version 1.14
*/
public static readonly V1_14 = KubernetesVersion.of('1.14');
/**
* Kubernetes version 1.15
*/
public static readonly V1_15 = KubernetesVersion.of('1.15');
/**
* Kubernetes version 1.16
*/
public static readonly V1_16 = KubernetesVersion.of('1.16');
/**
* Kubernetes version 1.17
*/
public static readonly V1_17 = KubernetesVersion.of('1.17');
/**
* Kubernetes version 1.18
*/
public static readonly V1_18 = KubernetesVersion.of('1.18');
/**
* Custom cluster version
* @param version custom version number
*/
public static of(version: string) { return new KubernetesVersion(version); }
/**
*
* @param version cluster version number
*/
private constructor(public readonly version: string) { }
}
abstract class ClusterBase extends Resource implements ICluster {
public abstract readonly connections: ec2.Connections;
public abstract readonly vpc: ec2.IVpc;
public abstract readonly clusterName: string;
public abstract readonly clusterArn: string;
public abstract readonly clusterEndpoint: string;
public abstract readonly clusterCertificateAuthorityData: string;
public abstract readonly clusterSecurityGroupId: string;
public abstract readonly clusterEncryptionConfigKeyArn: string;
public abstract readonly kubectlRole?: iam.IRole;
public abstract readonly kubectlEnvironment?: { [key: string]: string };
public abstract readonly kubectlSecurityGroup?: ec2.ISecurityGroup;
public abstract readonly kubectlPrivateSubnets?: ec2.ISubnet[];
public abstract readonly openIdConnectProvider: iam.IOpenIdConnectProvider;
/**
* Defines a Kubernetes resource in this cluster.
*
* The manifest will be applied/deleted using kubectl as needed.
*
* @param id logical id of this manifest
* @param manifest a list of Kubernetes resource specifications
* @returns a `KubernetesResource` object.
*/
public addManifest(id: string, ...manifest: Record<string, any>[]): KubernetesManifest {
return new KubernetesManifest(this, `manifest-${id}`, { cluster: this, manifest });
}
/**
* Defines a Helm chart in this cluster.
*
* @param id logical id of this chart.
* @param options options of this chart.
* @returns a `HelmChart` construct
*/
public addHelmChart(id: string, options: HelmChartOptions): HelmChart {
return new HelmChart(this, `chart-${id}`, { cluster: this, ...options });
}
/**
* Defines a CDK8s chart in this cluster.
*
* @param id logical id of this chart.
* @param chart the cdk8s chart.
* @returns a `KubernetesManifest` construct representing the chart.
*/
public addCdk8sChart(id: string, chart: Construct): KubernetesManifest {
const cdk8sChart = chart as any;
// see https://github.com/awslabs/cdk8s/blob/master/packages/cdk8s/src/chart.ts#L84
if (typeof cdk8sChart.toJson !== 'function') {
throw new Error(`Invalid cdk8s chart. Must contain a 'toJson' method, but found ${typeof cdk8sChart.toJson}`);
}
return this.addManifest(id, ...cdk8sChart.toJson());
}
public addServiceAccount(id: string, options: ServiceAccountOptions = {}): ServiceAccount {
return new ServiceAccount(this, id, {
...options,
cluster: this,
});
}
}
/**
* Options for fetching a ServiceLoadBalancerAddress.
*/
export interface ServiceLoadBalancerAddressOptions {
/**
* Timeout for waiting on the load balancer address.
*
* @default Duration.minutes(5)
*/
readonly timeout?: Duration;
/**
* The namespace the service belongs to.
*
* @default 'default'
*/
readonly namespace?: string;
}
/**
* A Cluster represents a managed Kubernetes Service (EKS)
*
* This is a fully managed cluster of API Servers (control-plane)
* The user is still required to create the worker nodes.
*/
export class Cluster extends ClusterBase {
/**
* Import an existing cluster
*
* @param scope the construct scope, in most cases 'this'
* @param id the id or name to import as
* @param attrs the cluster properties to use for importing information
*/
public static fromClusterAttributes(scope: Construct, id: string, attrs: ClusterAttributes): ICluster {
return new ImportedCluster(scope, id, attrs);
}
/**
* The VPC in which this Cluster was created
*/
public readonly vpc: ec2.IVpc;
/**
* The Name of the created EKS Cluster
*/
public readonly clusterName: string;
/**
* The AWS generated ARN for the Cluster resource
*
* @example arn:aws:eks:us-west-2:666666666666:cluster/prod
*/
public readonly clusterArn: string;
/**
* The endpoint URL for the Cluster
*
* This is the URL inside the kubeconfig file to use with kubectl
*
* @example https://5E1D0CEXAMPLEA591B746AFC5AB30262.yl4.us-west-2.eks.amazonaws.com
*/
public readonly clusterEndpoint: string;
/**
* The certificate-authority-data for your cluster.
*/
public readonly clusterCertificateAuthorityData: string;
/**
* The cluster security group that was created by Amazon EKS for the cluster.
*/
public readonly clusterSecurityGroupId: string;
/**
* Amazon Resource Name (ARN) or alias of the customer master key (CMK).
*/
public readonly clusterEncryptionConfigKeyArn: string;
/**
* Manages connection rules (Security Group Rules) for the cluster
*
* @type {ec2.Connections}
* @memberof Cluster
*/
public readonly connections: ec2.Connections;
/**
* IAM role assumed by the EKS Control Plane
*/
public readonly role: iam.IRole;
/**
* The auto scaling group that hosts the default capacity for this cluster.
* This will be `undefined` if the `defaultCapacityType` is not `EC2` or
* `defaultCapacityType` is `EC2` but default capacity is set to 0.
*/
public readonly defaultCapacity?: autoscaling.AutoScalingGroup;
/**
* The node group that hosts the default capacity for this cluster.
* This will be `undefined` if the `defaultCapacityType` is `EC2` or
* `defaultCapacityType` is `NODEGROUP` but default capacity is set to 0.
*/
public readonly defaultNodegroup?: Nodegroup;
/**
* An IAM role that can perform kubectl operations against this cluster.
*
* The role should be mapped to the `system:masters` Kubernetes RBAC role.
*/
public readonly kubectlRole?: iam.IRole;
/**
* Custom environment variables when running `kubectl` against this cluster.
* @default - no additional environment variables
*/
public readonly kubectlEnvironment?: { [key: string]: string };
/**
* A security group to use for `kubectl` execution.
*
* @default - If not specified, the k8s endpoint is expected to be accessible
* publicly.
*/
public readonly kubectlSecurityGroup?: ec2.ISecurityGroup;
/**
* Subnets to host the `kubectl` compute resources.
*
* @default - If not specified, the k8s endpoint is expected to be accessible
* publicly.
*/
public readonly kubectlPrivateSubnets?: ec2.ISubnet[];
/**
* An IAM role with administrative permissions to create or update the
* cluster. This role also has `systems:master` permissions.
*/
public readonly adminRole: iam.Role;
/**
* If the cluster has one (or more) FargateProfiles associated, this array
* will hold a reference to each.
*/
private readonly _fargateProfiles: FargateProfile[] = [];
/**
* an Open ID Connect Provider instance
*/
private _openIdConnectProvider?: iam.IOpenIdConnectProvider;
/**
* The AWS Lambda layer that contains `kubectl`, `helm` and the AWS CLI. If
* undefined, a SAR app that contains this layer will be used.
*/
public readonly kubectlLayer?: lambda.ILayerVersion;
/**
* If this cluster is kubectl-enabled, returns the `ClusterResource` object
* that manages it. If this cluster is not kubectl-enabled (i.e. uses the
* stock `CfnCluster`), this is `undefined`.
*/
private readonly _clusterResource: ClusterResource;
/**
* Manages the aws-auth config map.
*/
private _awsAuth?: AwsAuth;
private _spotInterruptHandler?: HelmChart;
private _neuronDevicePlugin?: KubernetesManifest;
private readonly endpointAccess: EndpointAccess;
private readonly vpcSubnets: ec2.SubnetSelection[];
private readonly version: KubernetesVersion;
/**
* A dummy CloudFormation resource that is used as a wait barrier which
* represents that the cluster is ready to receive "kubectl" commands.
*
* Specifically, all fargate profiles are automatically added as a dependency
* of this barrier, which means that it will only be "signaled" when all
* fargate profiles have been successfully created.
*
* When kubectl resources call `_attachKubectlResourceScope()`, this resource
* is added as their dependency which implies that they can only be deployed
* after the cluster is ready.
*/
private readonly _kubectlReadyBarrier: CfnResource;
private readonly _kubectlResourceProvider: KubectlProvider;
/**
* Initiates an EKS Cluster with the supplied arguments
*
* @param scope a Construct, most likely a cdk.Stack created
* @param id the id of the Construct to create
* @param props properties in the IClusterProps interface
*/
constructor(scope: Construct, id: string, props: ClusterProps) {
super(scope, id, {
physicalName: props.clusterName,
});
if (props.kubectlEnabled === false) {
throw new Error(
'The "eks.Cluster" class no longer allows disabling kubectl support. ' +
'As a temporary workaround, you can use the drop-in replacement class `eks.LegacyCluster`, ' +
'but bear in mind that this class will soon be removed and will no longer receive additional ' +
'features or bugfixes. See https://github.com/aws/aws-cdk/issues/9332 for more details');
}
const stack = Stack.of(this);
this.vpc = props.vpc || new ec2.Vpc(this, 'DefaultVpc');
this.version = props.version;
this.tagSubnets();
// this is the role used by EKS when interacting with AWS resources
this.role = props.role || new iam.Role(this, 'Role', {
assumedBy: new iam.ServicePrincipal('eks.amazonaws.com'),
managedPolicies: [
iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonEKSClusterPolicy'),
],
});
const securityGroup = props.securityGroup || new ec2.SecurityGroup(this, 'ControlPlaneSecurityGroup', {
vpc: this.vpc,
description: 'EKS Control Plane Security Group',
});
this.vpcSubnets = props.vpcSubnets ?? [{ subnetType: ec2.SubnetType.PUBLIC }, { subnetType: ec2.SubnetType.PRIVATE }];
// Get subnetIds for all selected subnets
const subnetIds = [...new Set(Array().concat(...this.vpcSubnets.map(s => this.vpc.selectSubnets(s).subnetIds)))];
this.endpointAccess = props.endpointAccess ?? EndpointAccess.PUBLIC_AND_PRIVATE;
this.kubectlEnvironment = props.kubectlEnvironment;
this.kubectlLayer = props.kubectlLayer;
const privateSubents = this.selectPrivateSubnets().slice(0, 16);
const publicAccessDisabled = !this.endpointAccess._config.publicAccess;
const publicAccessRestricted = !publicAccessDisabled
&& this.endpointAccess._config.publicCidrs
&& this.endpointAccess._config.publicCidrs.length !== 0;
// validate endpoint access configuration
if (privateSubents.length === 0 && publicAccessDisabled) {
// no private subnets and no public access at all, no good.
throw new Error('Vpc must contain private subnets when public endpoint access is disabled');
}
if (privateSubents.length === 0 && publicAccessRestricted) {
// no private subents and public access is restricted, no good.
throw new Error('Vpc must contain private subnets when public endpoint access is restricted');
}
const resource = this._clusterResource = new ClusterResource(this, 'Resource', {
name: this.physicalName,
roleArn: this.role.roleArn,
version: props.version.version,
resourcesVpcConfig: {
securityGroupIds: [securityGroup.securityGroupId],
subnetIds,
},
...(props.secretsEncryptionKey ? {
encryptionConfig: [{
provider: {
keyArn: props.secretsEncryptionKey.keyArn,
},
resources: ['secrets'],
}],
} : {} ),
endpointPrivateAccess: this.endpointAccess._config.privateAccess,
endpointPublicAccess: this.endpointAccess._config.publicAccess,
publicAccessCidrs: this.endpointAccess._config.publicCidrs,
secretsEncryptionKey: props.secretsEncryptionKey,
vpc: this.vpc,
});
if (this.endpointAccess._config.privateAccess && privateSubents.length !== 0) {
// when private access is enabled and the vpc has private subnets, lets connect
// the provider to the vpc so that it will work even when restricting public access.
// validate VPC properties according to: https://docs.aws.amazon.com/eks/latest/userguide/cluster-endpoint.html
if (this.vpc instanceof ec2.Vpc && !(this.vpc.dnsHostnamesEnabled && this.vpc.dnsSupportEnabled)) {
throw new Error('Private endpoint access requires the VPC to have DNS support and DNS hostnames enabled. Use `enableDnsHostnames: true` and `enableDnsSupport: true` when creating the VPC.');
}
this.kubectlPrivateSubnets = privateSubents;
// the vpc must exist in order to properly delete the cluster (since we run `kubectl delete`).
// this ensures that.
this._clusterResource.node.addDependency(this.vpc);
}
this.adminRole = resource.adminRole;
// we use an SSM parameter as a barrier because it's free and fast.
this._kubectlReadyBarrier = new CfnResource(this, 'KubectlReadyBarrier', {
type: 'AWS::SSM::Parameter',
properties: {
Type: 'String',
Value: 'aws:cdk:eks:kubectl-ready',
},
});