-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
cluster.ts
1228 lines (1070 loc) · 38.8 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 autoscaling from '@aws-cdk/aws-autoscaling';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as iam from '@aws-cdk/aws-iam';
import * as ssm from '@aws-cdk/aws-ssm';
import { CfnOutput, Construct, IResource, Resource, Stack, Tag, Token } from '@aws-cdk/core';
import { AwsAuth } from './aws-auth';
import { clusterArnComponents, ClusterResource } from './cluster-resource';
import { CfnCluster, CfnClusterProps } from './eks.generated';
import { FargateProfile, FargateProfileOptions } from './fargate-profile';
import { HelmChart, HelmChartOptions } from './helm-chart';
import { KubernetesPatch } from './k8s-patch';
import { KubernetesResource } from './k8s-resource';
import { KubectlProvider } from './kubectl-provider';
import { Nodegroup, NodegroupOptions } from './managed-nodegroup';
import { ServiceAccount, ServiceAccountOptions } from './service-account';
import { LifecycleLabel, renderAmazonLinuxUserData, renderBottlerocketUserData } from './user-data';
// 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;
}
/**
* Attributes for EKS clusters.
*/
export interface ClusterAttributes {
/**
* The VPC in which this Cluster was created
*/
readonly vpc: ec2.IVpc;
/**
* The physical name of the Cluster
*/
readonly clusterName: string;
/**
* The unique ARN assigned to the service by AWS
* in the form of arn:aws:eks:
*/
readonly clusterArn: string;
/**
* The API Server endpoint URL
*/
readonly clusterEndpoint: string;
/**
* The certificate-authority-data for your cluster.
*/
readonly clusterCertificateAuthorityData: string;
/**
* The cluster security group that was created by Amazon EKS for the cluster.
*/
readonly clusterSecurityGroupId: string;
/**
* Amazon Resource Name (ARN) or alias of the customer master key (CMK).
*/
readonly clusterEncryptionConfigKeyArn: string;
/**
* The security groups associated with this cluster.
*/
readonly securityGroups: ec2.ISecurityGroup[];
}
/**
* Options for configuring an EKS cluster.
*/
export interface ClusterOptions {
/**
* 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
*
* @default - If not supplied, will use Amazon default version
*/
readonly version?: string;
/**
* 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 - By default, it will only possible to update this Kubernetes
* system by adding resources to this cluster via `addResource` or
* by defining `KubernetesResource` resources in your AWS CDK app.
* Use this if you wish to grant cluster administration privileges
* to another role.
*/
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 name of the cluster
* will be synthesized.
*
* @default false
*/
readonly outputClusterName?: boolean;
/**
* 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;
/**
* 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;
}
/**
* Configuration props for EKS clusters.
*/
export interface ClusterProps extends ClusterOptions {
/**
* Allows defining `kubectrl`-related resources on this cluster.
*
* If this is disabled, it will not be possible to use the following
* capabilities:
* - `addResource`
* - `addRoleMapping`
* - `addUserMapping`
* - `addMastersRole` and `props.mastersRole`
*
* If this is disabled, the cluster can only be managed by issuing `kubectl`
* commands from a session that uses the IAM role/user that created the
* account.
*
* _NOTE_: changing this value will destoy the cluster. This is because a
* managable cluster must be created using an AWS CloudFormation custom
* resource which executes with an IAM role owned by the CDK app.
*
* @default true The cluster can be managed by the AWS CDK application.
*/
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.addCapacity` 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;
}
/**
* 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 Resource implements ICluster {
/**
* 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;
/**
* Indicates if `kubectl` related operations can be performed on this cluster.
*/
public readonly kubectlEnabled: boolean;
/**
* 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;
/**
* If the cluster has one (or more) FargateProfiles associated, this array
* will hold a reference to each.
*/
private readonly _fargateProfiles: FargateProfile[] = [];
/**
* 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 _openIdConnectProvider?: iam.OpenIdConnectProvider;
private _spotInterruptHandler?: HelmChart;
private readonly version: string | undefined;
/**
* Initiates an EKS Cluster with the supplied arguments
*
* @param scope a Construct, most likely a cdk.Stack created
* @param name the name 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,
});
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.connections = new ec2.Connections({
securityGroups: [securityGroup],
defaultPort: ec2.Port.tcp(443), // Control Plane has an HTTPS API
});
// Get subnetIds for all selected subnets
const placements = props.vpcSubnets || [{ subnetType: ec2.SubnetType.PUBLIC }, { subnetType: ec2.SubnetType.PRIVATE }];
const subnetIds = [...new Set(Array().concat(...placements.map(s => this.vpc.selectSubnets(s).subnetIds)))];
const clusterProps: CfnClusterProps = {
name: this.physicalName,
roleArn: this.role.roleArn,
version: props.version,
resourcesVpcConfig: {
securityGroupIds: [securityGroup.securityGroupId],
subnetIds,
},
};
let resource;
this.kubectlEnabled = props.kubectlEnabled === undefined ? true : props.kubectlEnabled;
if (this.kubectlEnabled) {
resource = new ClusterResource(this, 'Resource', clusterProps);
this._clusterResource = resource;
} else {
resource = new CfnCluster(this, 'Resource', clusterProps);
}
this.clusterName = this.getResourceNameAttribute(resource.ref);
this.clusterArn = this.getResourceArnAttribute(resource.attrArn, clusterArnComponents(this.physicalName));
this.clusterEndpoint = resource.attrEndpoint;
this.clusterCertificateAuthorityData = resource.attrCertificateAuthorityData;
this.clusterSecurityGroupId = resource.attrClusterSecurityGroupId;
this.clusterEncryptionConfigKeyArn = resource.attrEncryptionConfigKeyArn;
const updateConfigCommandPrefix = `aws eks update-kubeconfig --name ${this.clusterName}`;
const getTokenCommandPrefix = `aws eks get-token --cluster-name ${this.clusterName}`;
const commonCommandOptions = [ `--region ${stack.region}` ];
if (props.outputClusterName) {
new CfnOutput(this, 'ClusterName', { value: this.clusterName });
}
// map the IAM role to the `system:masters` group.
if (props.mastersRole) {
if (!this.kubectlEnabled) {
throw new Error('Cannot specify a "masters" role if kubectl is disabled');
}
this.awsAuth.addMastersRole(props.mastersRole);
if (props.outputMastersRoleArn) {
new CfnOutput(this, 'MastersRoleArn', { value: props.mastersRole.roleArn });
}
commonCommandOptions.push(`--role-arn ${props.mastersRole.roleArn}`);
}
// allocate default capacity if non-zero (or default).
const minCapacity = props.defaultCapacity === undefined ? DEFAULT_CAPACITY_COUNT : props.defaultCapacity;
if (minCapacity > 0) {
const instanceType = props.defaultCapacityInstance || DEFAULT_CAPACITY_TYPE;
this.defaultCapacity = props.defaultCapacityType === DefaultCapacityType.EC2 ?
this.addCapacity('DefaultCapacity', { instanceType, minCapacity }) : undefined;
this.defaultNodegroup = props.defaultCapacityType !== DefaultCapacityType.EC2 ?
this.addNodegroup('DefaultCapacity', { instanceType, minSize: minCapacity }) : undefined;
}
const outputConfigCommand = props.outputConfigCommand === undefined ? true : props.outputConfigCommand;
if (outputConfigCommand) {
const postfix = commonCommandOptions.join(' ');
new CfnOutput(this, 'ConfigCommand', { value: `${updateConfigCommandPrefix} ${postfix}` });
new CfnOutput(this, 'GetTokenCommand', { value: `${getTokenCommandPrefix} ${postfix}` });
}
if (this.kubectlEnabled) {
this.defineCoreDnsComputeType(props.coreDnsComputeType || CoreDnsComputeType.EC2);
}
}
/**
* Add nodes to this EKS cluster
*
* The nodes will automatically be configured with the right VPC and AMI
* for the instance type and Kubernetes version.
*
* Spot instances will be labeled `lifecycle=Ec2Spot` and tainted with `PreferNoSchedule`.
* If kubectl is enabled, the
* [spot interrupt handler](https://github.com/awslabs/ec2-spot-labs/tree/master/ec2-spot-eks-solution/spot-termination-handler)
* daemon will be installed on all spot instances to handle
* [EC2 Spot Instance Termination Notices](https://aws.amazon.com/blogs/aws/new-ec2-spot-instance-termination-notices/).
*/
public addCapacity(id: string, options: CapacityOptions): autoscaling.AutoScalingGroup {
if (options.machineImageType === MachineImageType.BOTTLEROCKET && options.bootstrapOptions !== undefined ) {
throw new Error('bootstrapOptions is not supported for Bottlerocket');
}
const asg = new autoscaling.AutoScalingGroup(this, id, {
...options,
vpc: this.vpc,
machineImage: options.machineImageType === MachineImageType.BOTTLEROCKET ?
new BottleRocketImage() :
new EksOptimizedImage({
nodeType: nodeTypeForInstanceType(options.instanceType),
kubernetesVersion: this.version,
}),
updateType: options.updateType || autoscaling.UpdateType.ROLLING_UPDATE,
instanceType: options.instanceType,
});
this.addAutoScalingGroup(asg, {
mapRole: options.mapRole,
bootstrapOptions: options.bootstrapOptions,
bootstrapEnabled: options.bootstrapEnabled,
machineImageType: options.machineImageType,
});
return asg;
}
/**
* Add managed nodegroup to this Amazon EKS cluster
*
* This method will create a new managed nodegroup and add into the capacity.
*
* @see https://docs.aws.amazon.com/eks/latest/userguide/managed-node-groups.html
* @param id The ID of the nodegroup
* @param options options for creating a new nodegroup
*/
public addNodegroup(id: string, options?: NodegroupOptions): Nodegroup {
return new Nodegroup(this, `Nodegroup${id}`, {
cluster: this,
...options,
});
}
/**
* Add compute capacity to this EKS cluster in the form of an AutoScalingGroup
*
* The AutoScalingGroup must be running an EKS-optimized AMI containing the
* /etc/eks/bootstrap.sh script. This method will configure Security Groups,
* add the right policies to the instance role, apply the right tags, and add
* the required user data to the instance's launch configuration.
*
* Spot instances will be labeled `lifecycle=Ec2Spot` and tainted with `PreferNoSchedule`.
* If kubectl is enabled, the
* [spot interrupt handler](https://github.com/awslabs/ec2-spot-labs/tree/master/ec2-spot-eks-solution/spot-termination-handler)
* daemon will be installed on all spot instances to handle
* [EC2 Spot Instance Termination Notices](https://aws.amazon.com/blogs/aws/new-ec2-spot-instance-termination-notices/).
*
* Prefer to use `addCapacity` if possible.
*
* @see https://docs.aws.amazon.com/eks/latest/userguide/launch-workers.html
* @param autoScalingGroup [disable-awslint:ref-via-interface]
* @param options options for adding auto scaling groups, like customizing the bootstrap script
*/
public addAutoScalingGroup(autoScalingGroup: autoscaling.AutoScalingGroup, options: AutoScalingGroupOptions) {
// self rules
autoScalingGroup.connections.allowInternally(ec2.Port.allTraffic());
// Cluster to:nodes rules
autoScalingGroup.connections.allowFrom(this, ec2.Port.tcp(443));
autoScalingGroup.connections.allowFrom(this, ec2.Port.tcpRange(1025, 65535));
// Allow HTTPS from Nodes to Cluster
autoScalingGroup.connections.allowTo(this, ec2.Port.tcp(443));
// Allow all node outbound traffic
autoScalingGroup.connections.allowToAnyIpv4(ec2.Port.allTcp());
autoScalingGroup.connections.allowToAnyIpv4(ec2.Port.allUdp());
autoScalingGroup.connections.allowToAnyIpv4(ec2.Port.allIcmp());
const bootstrapEnabled = options.bootstrapEnabled !== undefined ? options.bootstrapEnabled : true;
if (options.bootstrapOptions && !bootstrapEnabled) {
throw new Error('Cannot specify "bootstrapOptions" if "bootstrapEnabled" is false');
}
if (bootstrapEnabled) {
const userData = options.machineImageType === MachineImageType.BOTTLEROCKET ?
renderBottlerocketUserData(this) :
renderAmazonLinuxUserData(this.clusterName, autoScalingGroup, options.bootstrapOptions);
autoScalingGroup.addUserData(...userData);
}
autoScalingGroup.role.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonEKSWorkerNodePolicy'));
autoScalingGroup.role.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonEKS_CNI_Policy'));
autoScalingGroup.role.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonEC2ContainerRegistryReadOnly'));
// EKS Required Tags
Tag.add(autoScalingGroup, `kubernetes.io/cluster/${this.clusterName}`, 'owned', {
applyToLaunchedInstances: true,
});
if (options.mapRole === true && !this.kubectlEnabled) {
throw new Error('Cannot map instance IAM role to RBAC if kubectl is disabled for the cluster');
}
// do not attempt to map the role if `kubectl` is not enabled for this
// cluster or if `mapRole` is set to false. By default this should happen.
const mapRole = options.mapRole === undefined ? true : options.mapRole;
if (mapRole && this.kubectlEnabled) {
// see https://docs.aws.amazon.com/en_us/eks/latest/userguide/add-user-role.html
this.awsAuth.addRoleMapping(autoScalingGroup.role, {
username: 'system:node:{{EC2PrivateDNSName}}',
groups: [
'system:bootstrappers',
'system:nodes',
],
});
} else {
// since we are not mapping the instance role to RBAC, synthesize an
// output so it can be pasted into `aws-auth-cm.yaml`
new CfnOutput(autoScalingGroup, 'InstanceRoleARN', {
value: autoScalingGroup.role.roleArn,
});
}
// if this is an ASG with spot instances, install the spot interrupt handler (only if kubectl is enabled).
if (autoScalingGroup.spotPrice && this.kubectlEnabled) {
this.addSpotInterruptHandler();
}
}
/**
* Lazily creates the AwsAuth resource, which manages AWS authentication mapping.
*/
public get awsAuth() {
if (!this.kubectlEnabled) {
throw new Error('Cannot define aws-auth mappings if kubectl is disabled');
}
if (!this._awsAuth) {
this._awsAuth = new AwsAuth(this, 'AwsAuth', { cluster: this });
}
return this._awsAuth;
}
/**
* If this cluster is kubectl-enabled, returns the OpenID Connect issuer url.
* This is because the values is only be retrieved by the API and not exposed
* by CloudFormation. If this cluster is not kubectl-enabled (i.e. uses the
* stock `CfnCluster`), this is `undefined`.
* @attribute
*/
public get clusterOpenIdConnectIssuerUrl(): string {
if (!this._clusterResource) {
throw new Error('unable to obtain OpenID Connect issuer URL. Cluster must be kubectl-enabled');
}
return this._clusterResource.attrOpenIdConnectIssuerUrl;
}
/**
* If this cluster is kubectl-enabled, returns the OpenID Connect issuer.
* This is because the values is only be retrieved by the API and not exposed
* by CloudFormation. If this cluster is not kubectl-enabled (i.e. uses the
* stock `CfnCluster`), this is `undefined`.
* @attribute
*/
public get clusterOpenIdConnectIssuer(): string {
if (!this._clusterResource) {
throw new Error('unable to obtain OpenID Connect issuer. Cluster must be kubectl-enabled');
}
return this._clusterResource.attrOpenIdConnectIssuer;
}
/**
* An `OpenIdConnectProvider` resource associated with this cluster, and which can be used
* to link this cluster to AWS IAM.
*
* A provider will only be defined if this property is accessed (lazy initialization).
*/
public get openIdConnectProvider() {
if (!this.kubectlEnabled) {
throw new Error('Cannot specify a OpenID Connect Provider if kubectl is disabled');
}
if (!this._openIdConnectProvider) {
this._openIdConnectProvider = new iam.OpenIdConnectProvider(this, 'OpenIdConnectProvider', {
url: this.clusterOpenIdConnectIssuerUrl,
clientIds: [ 'sts.amazonaws.com' ],
/**
* For some reason EKS isn't validating the root certificate but a intermediat certificate
* which is one level up in the tree. Because of the a constant thumbprint value has to be
* stated with this OpenID Connect provider. The certificate thumbprint is the same for all the regions.
*/
thumbprints: [ '9e99a48a9960b14926bb7f3b02e22da2b0ab7280' ],
});
}
return this._openIdConnectProvider;
}
/**
* 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.
* @throws If `kubectlEnabled` is `false`
*/
public addResource(id: string, ...manifest: any[]) {
return new KubernetesResource(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` object
* @throws If `kubectlEnabled` is `false`
*/
public addChart(id: string, options: HelmChartOptions) {
return new HelmChart(this, `chart-${id}`, { cluster: this, ...options });
}
/**
* Adds a Fargate profile to this cluster.
* @see https://docs.aws.amazon.com/eks/latest/userguide/fargate-profile.html
*
* @param id the id of this profile
* @param options profile options
*/
public addFargateProfile(id: string, options: FargateProfileOptions) {
return new FargateProfile(this, `fargate-profile-${id}`, {
...options,
cluster: this,
});
}
/**
* Adds a service account to this cluster.
*
* @param id the id of this service account
* @param options service account options
*/
public addServiceAccount(id: string, options: ServiceAccountOptions = { }) {
return new ServiceAccount(this, id, {
...options,
cluster: this,
});
}
/**
* Returns the role ARN for the cluster creation role for kubectl-enabled
* clusters.
* @param assumedBy The IAM that will assume this role. If omitted, the
* creation role will be returned witout modification of its trust policy.
*
* @internal
*/
public get _kubectlCreationRole() {
if (!this._clusterResource) {
throw new Error('Unable to perform this operation since kubectl is not enabled for this cluster');
}
return this._clusterResource.creationRole;
}
/**
* Returns the custom resource provider for kubectl-related resources.
* @internal
*/
public get _kubectlProvider(): KubectlProvider {
if (!this._clusterResource) {
throw new Error('Unable to perform this operation since kubectl is not enabled for this cluster');
}
const uid = '@aws-cdk/aws-eks.KubectlProvider';
const provider = this.stack.node.tryFindChild(uid) as KubectlProvider || new KubectlProvider(this.stack, uid);
// allow the kubectl provider to assume the cluster creation role.
this._clusterResource.addTrustedRole(provider.role);
return provider;
}
/**
* Internal API used by `FargateProfile` to keep inventory of Fargate profiles associated with
* this cluster, for the sake of ensuring the profiles are created sequentially.
*
* @returns the list of FargateProfiles attached to this cluster, including the one just attached.
* @internal
*/
public _attachFargateProfile(fargateProfile: FargateProfile): FargateProfile[] {
this._fargateProfiles.push(fargateProfile);
return this._fargateProfiles;
}
/**
* Installs the AWS spot instance interrupt handler on the cluster if it's not
* already added.
*/
private addSpotInterruptHandler() {
if (!this._spotInterruptHandler) {
this._spotInterruptHandler = this.addChart('spot-interrupt-handler', {
chart: 'aws-node-termination-handler',
version: '0.7.3',
repository: 'https://aws.github.io/eks-charts',
namespace: 'kube-system',
values: {
'nodeSelector.lifecycle': LifecycleLabel.SPOT,
},
});
}
return this._spotInterruptHandler;
}
/**
* Opportunistically tag subnets with the required tags.
*
* If no subnets could be found (because this is an imported VPC), add a warning.
*
* @see https://docs.aws.amazon.com/eks/latest/userguide/network_reqs.html
*/
private tagSubnets() {
const tagAllSubnets = (type: string, subnets: ec2.ISubnet[], tag: string) => {
for (const subnet of subnets) {
// if this is not a concrete subnet, attach a construct warning
if (!ec2.Subnet.isVpcSubnet(subnet)) {
// message (if token): "could not auto-tag public/private subnet with tag..."
// message (if not token): "count not auto-tag public/private subnet xxxxx with tag..."
const subnetID = Token.isUnresolved(subnet.subnetId) ? '' : ` ${subnet.subnetId}`;
this.node.addWarning(`Could not auto-tag ${type} subnet${subnetID} with "${tag}=1", please remember to do this manually`);
continue;
}
subnet.node.applyAspect(new Tag(tag, '1'));
}
};
// https://docs.aws.amazon.com/eks/latest/userguide/network_reqs.html
tagAllSubnets('private', this.vpc.privateSubnets, 'kubernetes.io/role/internal-elb');
tagAllSubnets('public', this.vpc.publicSubnets, 'kubernetes.io/role/elb');
}
/**
* Patches the CoreDNS deployment configuration and sets the "eks.amazonaws.com/compute-type"
* annotation to either "ec2" or "fargate". Note that if "ec2" is selected, the resource is
* omitted/removed, since the cluster is created with the "ec2" compute type by default.
*/
private defineCoreDnsComputeType(type: CoreDnsComputeType) {
if (!this.kubectlEnabled) {
throw new Error('kubectl must be enabled in order to define the compute type for CoreDNS');
}
// ec2 is the "built in" compute type of the cluster so if this is the
// requested type we can simply omit the resource. since the resource's
// `restorePatch` is configured to restore the value to "ec2" this means
// that deletion of the resource will change to "ec2" as well.
if (type === CoreDnsComputeType.EC2) {
return;
}
// this is the json patch we merge into the resource based off of:
// https://docs.aws.amazon.com/eks/latest/userguide/fargate-getting-started.html#fargate-gs-coredns
const renderPatch = (computeType: CoreDnsComputeType) => ({
spec: {
template: {
metadata: {
annotations: {
'eks.amazonaws.com/compute-type': computeType,
},
},
},
},
});
new KubernetesPatch(this, 'CoreDnsComputeTypePatch', {
cluster: this,
resourceName: 'deployment/coredns',
resourceNamespace: 'kube-system',
applyPatch: renderPatch(CoreDnsComputeType.FARGATE),
restorePatch: renderPatch(CoreDnsComputeType.EC2),
});
}
}
/**
* Options for adding worker nodes
*/
export interface CapacityOptions extends autoscaling.CommonAutoScalingGroupProps {
/**
* Instance type of the instances to start
*/
readonly instanceType: ec2.InstanceType;
/**
* Will automatically update the aws-auth ConfigMap to map the IAM instance
* role to RBAC.
*
* This cannot be explicitly set to `true` if the cluster has kubectl disabled.
*
* @default - true if the cluster has kubectl enabled (which is the default).
*/
readonly mapRole?: boolean;
/**
* Configures the EC2 user-data script for instances in this autoscaling group
* to bootstrap the node (invoke `/etc/eks/bootstrap.sh`) and associate it
* with the EKS cluster.
*
* If you wish to provide a custom user data script, set this to `false` and
* manually invoke `autoscalingGroup.addUserData()`.
*
* @default true
*/
readonly bootstrapEnabled?: boolean;
/**
* EKS node bootstrapping options.
*
* @default - none
*/
readonly bootstrapOptions?: BootstrapOptions;
/**
* Machine image type
*
* @default MachineImageType.AMAZON_LINUX_2
*/
readonly machineImageType?: MachineImageType;
}
/**
* EKS node bootstrapping options.
*/
export interface BootstrapOptions {
/**
* Sets `--max-pods` for the kubelet based on the capacity of the EC2 instance.
*
* @default true
*/
readonly useMaxPods?: boolean;
/**
* Restores the docker default bridge network.
*
* @default false
*/
readonly enableDockerBridge?: boolean;
/**
* Number of retry attempts for AWS API call (DescribeCluster).
*
* @default 3
*/
readonly awsApiRetryAttempts?: number;
/**
* The contents of the `/etc/docker/daemon.json` file. Useful if you want a
* custom config differing from the default one in the EKS AMI.
*
* @default - none
*/
readonly dockerConfigJson?: string;
/**
* Extra arguments to add to the kubelet. Useful for adding labels or taints.
*
* @example --node-labels foo=bar,goo=far
* @default - none
*/
readonly kubeletExtraArgs?: string;
/**
* Additional command line arguments to pass to the `/etc/eks/bootstrap.sh`
* command.
*
* @see https://github.com/awslabs/amazon-eks-ami/blob/master/files/bootstrap.sh
* @default - none
*/