-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathcluster.ts
2429 lines (2232 loc) · 97.7 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
// Copyright 2016-2022, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as aws from "@pulumi/aws";
import * as k8s from "@pulumi/kubernetes";
import * as pulumi from "@pulumi/pulumi";
import * as http from "http";
import * as https from "https";
import * as HttpsProxyAgent from "https-proxy-agent";
import * as process from "process";
import * as url from "url";
import {
createAccessEntries,
createAwsAuthData,
supportsConfigMap,
supportsAccessEntries,
validateAuthenticationMode,
} from "./authenticationMode";
import { getIssuerCAThumbprint } from "./cert-thumprint";
import { assertCompatibleAWSCLIExists } from "./dependencies";
import {
computeWorkerSubnets,
createNodeGroupV2,
NodeGroupBaseOptions,
NodeGroupV2Data,
} from "./nodegroup";
import { createNodeGroupSecurityGroup } from "./securitygroup";
import { ServiceRole } from "./servicerole";
import { createStorageClass, EBSVolumeType, StorageClass } from "./storageclass";
import { InputTags, UserStorageClasses } from "./utils";
import { VpcCniAddon, VpcCniAddonOptions } from "./cni-addon";
import { stringifyAddonConfiguration } from "./addon";
import { getRegionFromArn } from "./utilities";
/**
* RoleMapping describes a mapping from an AWS IAM role to a Kubernetes user and groups.
*/
export interface RoleMapping {
/**
* The ARN of the IAM role to add.
*/
roleArn: pulumi.Input<aws.ARN>;
/**
* The user name within Kubernetes to map to the IAM role. By default, the user name is the ARN of the IAM role.
*/
username: pulumi.Input<string>;
/**
* A list of groups within Kubernetes to which the role is mapped.
*/
groups: pulumi.Input<pulumi.Input<string>[]>;
}
/**
* UserMapping describes a mapping from an AWS IAM user to a Kubernetes user and groups.
*/
export interface UserMapping {
/**
* The ARN of the IAM user to add.
*/
userArn: pulumi.Input<aws.ARN>;
/**
* The user name within Kubernetes to map to the IAM user. By default, the user name is the ARN of the IAM user.
*/
username: pulumi.Input<string>;
/**
* A list of groups within Kubernetes to which the user is mapped to.
*/
groups: pulumi.Input<pulumi.Input<string>[]>;
}
/**
* CreationRoleProvider is a component containing the AWS Role and Provider necessary to override the `[system:master]`
* entity ARN. This is an optional argument used in `ClusterOptions`. Read more: https://docs.aws.amazon.com/eks/latest/userguide/add-user-role.html
*/
export interface CreationRoleProvider {
role: aws.iam.Role;
provider: pulumi.ProviderResource;
}
/**
* KubeconfigOptions represents the AWS credentials to scope a given kubeconfig
* when using a non-default credential chain.
*
* The options can be used independently, or additively.
*
* A scoped kubeconfig is necessary for certain auth scenarios. For example:
* 1. Assume a role on the default account caller,
* 2. Use an AWS creds profile instead of the default account caller,
* 3. Use an AWS creds creds profile instead of the default account caller,
* and then assume a given role on the profile. This scenario is also
* possible by only using a profile, iff the profile includes a role to
* assume in its settings.
*
* See for more details:
* - https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html
* - https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html
* - https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html
*/
export interface KubeconfigOptions {
/**
* Role ARN to assume instead of the default AWS credential provider chain.
*
* The role is passed to kubeconfig as an authentication exec argument.
*/
roleArn?: pulumi.Input<aws.ARN>;
/**
* AWS credential profile name to always use instead of the
* default AWS credential provider chain.
*
* The profile is passed to kubeconfig as an authentication environment
* setting.
*/
profileName?: pulumi.Input<string>;
}
/**
* CoreData defines the core set of data associated with an EKS cluster, including the network in which it runs.
*/
export interface CoreData {
cluster: aws.eks.Cluster;
vpcId: pulumi.Output<string>;
subnetIds: pulumi.Output<string[]>;
endpoint: pulumi.Output<string>;
clusterSecurityGroup?: aws.ec2.SecurityGroup;
provider: k8s.Provider;
instanceRoles: pulumi.Output<aws.iam.Role[]>;
nodeGroupOptions: ClusterNodeGroupOptions;
awsProvider?: pulumi.ProviderResource;
publicSubnetIds?: pulumi.Output<string[]>;
privateSubnetIds?: pulumi.Output<string[]>;
eksNodeAccess?: k8s.core.v1.ConfigMap;
storageClasses?: UserStorageClasses;
kubeconfig?: pulumi.Output<any>;
vpcCni?: VpcCniAddon;
tags?: InputTags;
nodeSecurityGroupTags?: InputTags;
fargateProfile: pulumi.Output<aws.eks.FargateProfile | undefined>;
oidcProvider?: aws.iam.OpenIdConnectProvider;
encryptionConfig?: pulumi.Output<aws.types.output.eks.ClusterEncryptionConfig>;
clusterIamRole: pulumi.Output<aws.iam.Role>;
accessEntries?: pulumi.Output<AccessEntry[]>;
autoModeNodeRoleName: pulumi.Output<string>;
}
function createOrGetInstanceProfile(
name: string,
parent: pulumi.ComponentResource,
instanceRoleName?: pulumi.Input<aws.iam.Role>,
instanceProfileName?: pulumi.Input<string>,
provider?: pulumi.ProviderResource,
): aws.iam.InstanceProfile {
let instanceProfile: aws.iam.InstanceProfile;
if (instanceProfileName) {
instanceProfile = aws.iam.InstanceProfile.get(
`${name}-instanceProfile`,
instanceProfileName,
undefined,
{ parent, provider },
);
} else {
instanceProfile = new aws.iam.InstanceProfile(
`${name}-instanceProfile`,
{
role: instanceRoleName,
},
{ parent, provider },
);
}
return instanceProfile;
}
// ExecEnvVar sets the environment variables using an exec-based auth plugin.
interface ExecEnvVar {
/**
* Name of the auth exec environment variable.
*/
name: pulumi.Input<string>;
/**
* Value of the auth exec environment variable.
*/
value: pulumi.Input<string>;
}
/** @internal */
export function generateKubeconfig(
clusterName: pulumi.Input<string>,
clusterEndpoint: pulumi.Input<string>,
region: pulumi.Input<string>,
includeProfile: boolean,
certData?: pulumi.Input<string>,
opts?: KubeconfigOptions,
) {
let args = [
"--region",
region,
"eks",
"get-token",
"--cluster-name",
clusterName,
"--output",
"json",
];
const env: ExecEnvVar[] = [
{
name: "KUBERNETES_EXEC_INFO",
value: `{"apiVersion": "client.authentication.k8s.io/v1beta1"}`,
},
];
if (opts?.roleArn) {
args = [...args, "--role", opts.roleArn];
}
if (includeProfile && opts?.profileName) {
// Use --profile instead of AWS_PROFILE because the latter can be
// overridden by ambient credentials:
// https://docs.aws.amazon.com/cli/latest/topic/config-vars.html#id1
args = [...args, "--profile", opts.profileName];
}
return pulumi.all([args, env]).apply(([tokenArgs, envvars]) => {
return {
apiVersion: "v1",
clusters: [
{
cluster: {
server: clusterEndpoint,
"certificate-authority-data": certData,
},
name: "kubernetes",
},
],
contexts: [
{
context: {
cluster: "kubernetes",
user: "aws",
},
name: "aws",
},
],
"current-context": "aws",
kind: "Config",
users: [
{
name: "aws",
user: {
exec: {
apiVersion: "client.authentication.k8s.io/v1beta1",
command: "aws",
args: tokenArgs,
env: envvars,
},
},
},
],
};
});
}
export interface ClusterCreationRoleProviderOptions {
region?: pulumi.Input<aws.Region>;
profile?: pulumi.Input<string>;
}
export interface EksAutoModeOptions {
enabled: boolean;
createNodeRole?: boolean;
computeConfig?: pulumi.Input<aws.types.input.eks.ClusterComputeConfig>;
}
/**
* ClusterCreationRoleProvider is a component that wraps creating a role provider that can be passed to
* `new eks.Cluster("test", { creationRoleProvider: ... })`. This can be used to provide a
* specific role to use for the creation of the EKS cluster different from the role being used
* to run the Pulumi deployment.
*/
export class ClusterCreationRoleProvider
extends pulumi.ComponentResource
implements CreationRoleProvider
{
public readonly role: aws.iam.Role;
public readonly provider: pulumi.ProviderResource;
/**
* Creates a role provider that can be passed to `new eks.Cluster("test", { creationRoleProvider: ... })`.
* This can be used to provide a specific role to use for the creation of the EKS cluster different from
* the role being used to run the Pulumi deployment.
*
* @param name The _unique_ name of this component.
* @param args The arguments for this component.
* @param opts A bag of options that control this component's behavior.
*/
constructor(
name: string,
args: ClusterCreationRoleProviderOptions,
opts?: pulumi.ComponentResourceOptions,
) {
super("eks:index:ClusterCreationRoleProvider", name, args, opts);
const result = getRoleProvider(name, args?.region, args?.profile, this, opts?.provider);
this.role = result.role;
this.provider = result.provider;
this.registerOutputs(undefined);
}
}
/**
* getRoleProvider creates a role provider that can be passed to `new eks.Cluster("test", {
* creationRoleProvider: ... })`. This can be used to provide a specific role to use for the
* creation of the EKS cluster different from the role being used to run the Pulumi deployment.
*/
function getRoleProvider(
name: string,
region?: pulumi.Input<aws.Region>,
profile?: pulumi.Input<string>,
parent?: pulumi.ComponentResource,
provider?: pulumi.ProviderResource,
): CreationRoleProvider {
const partition = aws.getPartitionOutput({}, { parent }).partition;
const accountId = pulumi.output(aws.getCallerIdentity({}, { parent })).accountId;
const iamRole = new aws.iam.Role(
`${name}-eksClusterCreatorRole`,
{
assumeRolePolicy: pulumi.interpolate`{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:${partition}:iam::${accountId}:root"
},
"Action": "sts:AssumeRole"
}
]
}`,
description: `Admin access to eks-${name}`,
},
{ parent, provider },
);
// `eks:*` is needed to create/read/update/delete the EKS cluster, `iam:PassRole` is needed to pass the EKS service role to the cluster
// https://docs.aws.amazon.com/eks/latest/userguide/service_IAM_role.html
const rolePolicy = new aws.iam.RolePolicy(
`${name}-eksClusterCreatorPolicy`,
{
role: iamRole,
policy: {
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Action: "eks:*",
Resource: "*",
},
{
Effect: "Allow",
Action: "iam:PassRole",
Resource: "*",
},
],
},
},
{ parent: iamRole, provider },
);
const creatorProvider = new aws.Provider(
`${name}-eksClusterCreatorEntity`,
{
region: region,
profile: profile,
assumeRole: {
roleArn: iamRole.arn.apply(async (arn) => {
// wait 30 seconds to assume the IAM Role https://github.com/pulumi/pulumi-aws/issues/673
if (!pulumi.runtime.isDryRun()) {
await new Promise((resolve) => setTimeout(resolve, 30 * 1000));
}
return arn;
}),
},
},
{ parent: iamRole, provider },
);
return {
role: iamRole,
provider: creatorProvider,
};
}
/**
* Create the core components and settings required for the EKS cluster.
*/
export function createCore(
name: string,
rawArgs: ClusterOptions,
parent: pulumi.ComponentResource,
provider?: pulumi.ProviderResource,
): CoreData {
// Check to ensure that a compatible version of aws CLI is installed, as we'll need it in order
// to retrieve a token to login to the EKS cluster later.
assertCompatibleAWSCLIExists();
const args = validateAuthenticationMode(rawArgs);
if (args.instanceRole && args.instanceRoles) {
throw new Error(
"instanceRole and instanceRoles are mutually exclusive, and cannot both be set.",
);
}
if (args.subnetIds && (args.publicSubnetIds || args.privateSubnetIds)) {
throw new Error(
"subnetIds, and the use of publicSubnetIds and/or privateSubnetIds are mutually exclusive. Choose a single approach.",
);
}
if (
args.nodeGroupOptions &&
(args.nodeSubnetIds ||
args.nodeAssociatePublicIpAddress ||
args.instanceType ||
args.instanceProfileName ||
args.nodePublicKey ||
args.nodeRootVolumeSize ||
args.nodeUserData ||
args.minSize ||
args.maxSize ||
args.desiredCapacity ||
args.nodeAmiId ||
args.gpu)
) {
throw new Error(
"Setting nodeGroupOptions, and any set of singular node group option(s) on the cluster, is mutually exclusive. Choose a single approach.",
);
}
if (args.autoMode?.enabled && !supportsAccessEntries(args.authenticationMode)) {
throw new pulumi.ResourceError(
"Access entries are required when using EKS Auto Mode. Use the authentication mode 'API' or 'API_AND_CONFIG_MAP'.",
parent,
);
}
// Configure the node group options.
const nodeGroupOptions: ClusterNodeGroupOptions = args.nodeGroupOptions || {
nodeSubnetIds: args.nodeSubnetIds,
nodeAssociatePublicIpAddress: args.nodeAssociatePublicIpAddress,
instanceType: args.instanceType,
nodePublicKey: args.nodePublicKey,
nodeRootVolumeEncrypted: args.nodeRootVolumeEncrypted,
nodeRootVolumeSize: args.nodeRootVolumeSize,
nodeUserData: args.nodeUserData,
minSize: args.minSize,
maxSize: args.maxSize,
desiredCapacity: args.desiredCapacity,
amiId: args.nodeAmiId,
gpu: args.gpu,
version: args.version,
};
const { partition, dnsSuffix } = aws.getPartitionOutput({}, { parent });
// Configure default networking architecture.
let vpcId: pulumi.Input<string> = args.vpcId!;
let clusterSubnetIds: pulumi.Input<pulumi.Input<string>[]> = [];
// If no VPC is set, use the default VPC's subnets.
if (!args.vpcId) {
const invokeOpts = { parent, async: true };
const vpc = aws.ec2.getVpc({ default: true }, invokeOpts);
vpcId = vpc.then((v) => v.id);
clusterSubnetIds = vpc
.then((v) =>
aws.ec2.getSubnets({ filters: [{ name: "vpc-id", values: [v.id] }] }, invokeOpts),
)
.then((subnets) => subnets.ids);
}
// Form the subnetIds to use on the cluster from either:
// - subnetIds
// - A combination of privateSubnetIds and/or publicSubnetIds.
if (args.subnetIds !== undefined) {
clusterSubnetIds = args.subnetIds;
} else if (args.publicSubnetIds !== undefined || args.privateSubnetIds !== undefined) {
clusterSubnetIds = pulumi
.all([args.publicSubnetIds || [], args.privateSubnetIds || []])
.apply(([publicIds, privateIds]) => {
return [...publicIds, ...privateIds];
});
}
// Create the EKS service role
let eksServiceRole: ServiceRole | undefined;
if (!args.serviceRole) {
const managedPolicies = ["AmazonEKSClusterPolicy"];
// EKS auto mode requires additional managed policies
// see https://docs.aws.amazon.com/eks/latest/userguide/auto-enable-existing.html#_cli
if (args.autoMode?.enabled) {
managedPolicies.push(
"AmazonEKSComputePolicy",
"AmazonEKSBlockStoragePolicy",
"AmazonEKSLoadBalancingPolicy",
"AmazonEKSNetworkingPolicy",
);
}
eksServiceRole = new ServiceRole(
`${name}-eksRole`,
{
service: pulumi.interpolate`eks.${dnsSuffix}`,
description: "Allows EKS to manage clusters on your behalf.",
managedPolicyArns: managedPolicies.map((policy) => ({
id: `arn:aws:iam::aws:policy/${policy}`,
arn: pulumi.interpolate`arn:${partition}:iam::aws:policy/${policy}`,
})),
tags: args.tags,
// EKS Auto Mode needs "sts:TagSession" in addition to the default "sts:AssumeRole"
assumeRoleActions: ["sts:AssumeRole", "sts:TagSession"],
},
{ parent, provider },
);
}
// Do not create the default security group if the user makes an explicit decision or if EKS Auto Mode is enabled.
const skipDefaultSecurityGroups = args.skipDefaultSecurityGroups ?? args.autoMode?.enabled;
// Create the EKS cluster security group
let eksClusterSecurityGroup: aws.ec2.SecurityGroup | undefined;
if (args.clusterSecurityGroup) {
eksClusterSecurityGroup = args.clusterSecurityGroup;
} else if (!skipDefaultSecurityGroups) {
eksClusterSecurityGroup = new aws.ec2.SecurityGroup(
`${name}-eksClusterSecurityGroup`,
{
vpcId: vpcId,
revokeRulesOnDelete: true,
tags: pulumi.all([args.tags, args.clusterSecurityGroupTags]).apply(
([tags, clusterSecurityGroupTags]) =>
<aws.Tags>{
Name: `${name}-eksClusterSecurityGroup`,
...clusterSecurityGroupTags,
...tags,
},
),
},
{ parent, provider },
);
const eksClusterInternetEgressRule = new aws.ec2.SecurityGroupRule(
`${name}-eksClusterInternetEgressRule`,
{
description: "Allow internet access.",
type: "egress",
fromPort: 0,
toPort: 0,
protocol: "-1", // all
cidrBlocks: ["0.0.0.0/0"],
securityGroupId: eksClusterSecurityGroup.id,
},
{ parent, provider },
);
}
// Create the cluster encryption provider for using envelope encryption on
// Kubernetes secrets.
let encryptionProvider:
| pulumi.Output<aws.types.output.eks.ClusterEncryptionConfigProvider>
| undefined;
let encryptionConfig: pulumi.Output<aws.types.output.eks.ClusterEncryptionConfig> | undefined;
if (args.encryptionConfigKeyArn) {
encryptionProvider = pulumi.output(args.encryptionConfigKeyArn).apply(
(keyArn) =>
<aws.types.output.eks.ClusterEncryptionConfigProvider>{
keyArn,
},
);
encryptionConfig = encryptionProvider.apply(
(ep) =>
<aws.types.output.eks.ClusterEncryptionConfig>{
provider: ep,
resources: ["secrets"], // Only valid values are: "secrets"
},
);
}
let kubernetesNetworkConfig:
| pulumi.Output<aws.types.input.eks.ClusterKubernetesNetworkConfig>
| undefined;
if (args.kubernetesServiceIpAddressRange || args.ipFamily || args.autoMode?.enabled) {
kubernetesNetworkConfig = pulumi
.all([args.kubernetesServiceIpAddressRange, args.ipFamily])
.apply(([serviceIpv4Cidr, ipFamily = "ipv4"]) => ({
serviceIpv4Cidr: ipFamily === "ipv4" ? serviceIpv4Cidr : undefined, // only applicable for IPv4 IP family
ipFamily: ipFamily,
elasticLoadBalancing: args.autoMode?.enabled
? {
enabled: args.autoMode?.enabled,
}
: undefined,
}));
}
let eksAutoNodeRole: ServiceRole | undefined;
if (args.autoMode?.enabled && args.autoMode.createNodeRole !== false) {
eksAutoNodeRole = new ServiceRole(
`${name}-nodeRole`,
{
service: pulumi.interpolate`ec2.${dnsSuffix}`,
managedPolicyArns: [
{
id: "arn:aws:iam::aws:policy/AmazonEKSWorkerNodeMinimalPolicy",
arn: pulumi.interpolate`arn:${partition}:iam::aws:policy/AmazonEKSWorkerNodeMinimalPolicy`,
},
{
id: "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryPullOnly",
arn: pulumi.interpolate`arn:${partition}:iam::aws:policy/AmazonEC2ContainerRegistryPullOnly`,
},
],
tags: args.tags,
},
{ parent, provider },
);
}
let computeConfig: pulumi.Input<aws.types.input.eks.ClusterComputeConfig> | undefined;
if (args.autoMode?.enabled) {
computeConfig = pulumi.output(args.autoMode.computeConfig).apply((config) => {
return {
enabled: true,
nodeRoleArn: eksAutoNodeRole?.directRole.arn,
nodePools: ["general-purpose", "system"],
...config,
};
});
}
const storageConfig = args.autoMode?.enabled ? { blockStorage: { enabled: true } } : undefined;
// Create the EKS cluster
const eksCluster = new aws.eks.Cluster(
`${name}-eksCluster`,
{
name: args.name,
roleArn: args.serviceRole
? pulumi.output(args.serviceRole).arn
: eksServiceRole?.directRole.arn!,
computeConfig,
storageConfig,
// When a cluster is created with EKS Auto Mode, it must be created without the addons
bootstrapSelfManagedAddons: args.autoMode?.enabled ? false : undefined,
vpcConfig: {
securityGroupIds: eksClusterSecurityGroup
? [eksClusterSecurityGroup.id]
: undefined,
subnetIds: clusterSubnetIds,
endpointPrivateAccess: args.endpointPrivateAccess,
endpointPublicAccess: args.endpointPublicAccess,
publicAccessCidrs: args.publicAccessCidrs
? pulumi
.all([args.publicAccessCidrs, args.endpointPublicAccess ?? true])
.apply(([cidrs, publicAccess]) => {
if (!publicAccess && cidrs) {
throw new pulumi.ResourceError(
"`publicAccessCidrs` can only be set when `endpointPublicAccess` is true",
eksCluster,
);
}
return cidrs;
})
: undefined,
},
version: args.version,
enabledClusterLogTypes: args.enabledClusterLogTypes,
defaultAddonsToRemoves: args.defaultAddonsToRemove,
tags: pulumi.all([args.tags, args.clusterTags]).apply(
([tags, clusterTags]) =>
<aws.Tags>{
Name: `${name}-eksCluster`,
...clusterTags,
...tags,
},
),
encryptionConfig,
kubernetesNetworkConfig,
accessConfig: args.authenticationMode
? {
authenticationMode: args.authenticationMode,
// Explicitely grants the principal creating the cluster admin access to the cluster.
// This is the default behavior of EKS when no accessConfig is provided.
// It is required for this component because it deploys charts to the cluster.
bootstrapClusterCreatorAdminPermissions: true,
}
: undefined,
},
{
parent,
provider: args.creationRoleProvider ? args.creationRoleProvider.provider : provider,
// ignore changes to the bootstrapClusterCreatorAdminPermissions field because it has bi-modal default behavior
// in upstream and would cause replacements for users upgrading from older versions of the EKS provider (<=2.7.3).
// See https://github.com/pulumi/pulumi-aws/issues/3997#issuecomment-2223201333 for more details.
ignoreChanges: [
"accessConfig.bootstrapClusterCreatorAdminPermissions",
// bootstrapSelfManagedAddons is a creation time property and should not be updated
"bootstrapSelfManagedAddons",
],
dependsOn: [
// Ensure the service roles are created before the cluster and all policies are attached.
...(eksServiceRole ? [eksServiceRole.resolvedRole] : []),
...(eksAutoNodeRole ? [eksAutoNodeRole.resolvedRole] : []),
],
},
);
const kubeProxyAddonEnabled = args.kubeProxyAddonOptions?.enabled ?? !args.autoMode?.enabled;
if (kubeProxyAddonEnabled) {
const kubeProxyVersion: pulumi.Output<string> = args.kubeProxyAddonOptions?.version
? pulumi.output(args.kubeProxyAddonOptions?.version)
: aws.eks
.getAddonVersionOutput(
{
addonName: "kube-proxy",
kubernetesVersion: eksCluster.version,
mostRecent: true, // whether to return the default version or the most recent version for the specified kubernetes version
},
{ parent, provider },
)
.apply((addonVersion) => addonVersion.version);
const kubeProxyAddon = new aws.eks.Addon(
`${name}-kube-proxy`,
{
clusterName: eksCluster.name,
addonName: "kube-proxy",
preserve: true,
tags: args.tags,
resolveConflictsOnCreate:
args.kubeProxyAddonOptions?.resolveConflictsOnCreate ?? "OVERWRITE",
resolveConflictsOnUpdate:
args.kubeProxyAddonOptions?.resolveConflictsOnUpdate ?? "OVERWRITE",
addonVersion: kubeProxyVersion,
configurationValues: stringifyAddonConfiguration(
args.kubeProxyAddonOptions?.configurationValues,
),
},
{ parent, provider },
);
}
// Instead of using the kubeconfig directly, we also add a wait of up to 5 minutes or until we
// can reach the API server for the Output that provides access to the kubeconfig string so that
// there is time for the cluster API server to become completely available. Ideally we
// would rely on the EKS API only returning once this was available, but we have seen frequent
// cases where it is not yet available immediately after provisioning - possibly due to DNS
// propagation delay or other non-deterministic factors.
const endpoint = eksCluster.endpoint.apply(async (clusterEndpoint) => {
if (!pulumi.runtime.isDryRun() && args.endpointPublicAccess) {
// For up to 300 seconds, try to contact the API cluster healthz
// endpoint, and verify that it is reachable.
const healthz = `${clusterEndpoint}/healthz`;
const agent = createHttpAgent(args.proxy);
const maxRetries = 60;
const reqTimeoutMilliseconds = 1000; // HTTPS request timeout
const timeoutMilliseconds = 5000; // Retry timeout
for (let i = 0; i < maxRetries; i++) {
try {
await new Promise<void>((resolve, reject) => {
const options = {
...url.parse(healthz),
rejectUnauthorized: false, // EKS API server uses self-signed cert
agent: agent,
timeout: reqTimeoutMilliseconds,
};
const req = https.request(options, (res) => {
res.statusCode === 200 ? resolve(undefined) : reject(); // Verify healthz returns 200
});
req.on("timeout", reject);
req.on("error", reject);
req.end();
});
pulumi.log.info(`Cluster is ready`, eksCluster, undefined, true);
break;
} catch (e) {
const retrySecondsLeft = ((maxRetries - i) * timeoutMilliseconds) / 1000;
pulumi.log.info(
`Waiting up to (${retrySecondsLeft}) more seconds for cluster readiness...`,
eksCluster,
undefined,
true,
);
}
await new Promise((resolve) => setTimeout(resolve, timeoutMilliseconds));
}
}
return clusterEndpoint;
});
// Compute the required kubeconfig. Note that we do not export this value: we want the exported config to
// depend on the autoscaling group we'll create later so that nothing attempts to use the EKS cluster before
// its worker nodes have come up.
const genKubeconfig = (useProfileName: boolean) => {
const region = eksCluster.arn.apply(getRegionFromArn);
const kubeconfig = pulumi
.all([
eksCluster.name,
endpoint,
eksCluster.certificateAuthority,
args.providerCredentialOpts,
region,
])
.apply(
([
clusterName,
clusterEndpoint,
clusterCertificateAuthority,
providerCredentialOpts,
region,
]) => {
let config = {};
if (args.creationRoleProvider) {
config = args.creationRoleProvider.role.arn.apply((arn) => {
const opts: KubeconfigOptions = { roleArn: arn };
return generateKubeconfig(
clusterName,
clusterEndpoint,
region,
useProfileName,
clusterCertificateAuthority?.data,
opts,
);
});
} else if (providerCredentialOpts) {
config = generateKubeconfig(
clusterName,
clusterEndpoint,
region,
useProfileName,
clusterCertificateAuthority?.data,
providerCredentialOpts,
);
} else {
config = generateKubeconfig(
clusterName,
clusterEndpoint,
region,
useProfileName,
clusterCertificateAuthority?.data,
);
}
return config;
},
);
return kubeconfig;
};
// We need 2 forms of kubeconfig, one with the profile name and one without. The one with the profile name
// is required to interact with the cluster by this provider. The one without is used by the user to interact
// with the cluster and enable multi-user access.
const kubeconfig = genKubeconfig(true);
const kubeconfigWithoutProfile = genKubeconfig(false);
const k8sProvider = new k8s.Provider(
`${name}-eks-k8s`,
{
kubeconfig: kubeconfig.apply(JSON.stringify),
enableConfigMapMutable: args.enableConfigMapMutable,
},
{ parent: parent },
);
// create the default node group unless the user opts out of it or if Fargate/EKS Auto Mode is enabled
const skipDefaultNodeGroup =
args.skipDefaultNodeGroup || args.fargate || args.autoMode?.enabled;
let instanceRoles: pulumi.Output<aws.iam.Role[]>;
let defaultInstanceRole: pulumi.Output<aws.iam.Role> | undefined;
// Create role mappings of the instance roles specified for aws-auth.
if (args.instanceRoles) {
instanceRoles = pulumi.output(args.instanceRoles);
} else if (args.instanceRole) {
// Create an instance profile if using a default node group
if (!skipDefaultNodeGroup) {
nodeGroupOptions.instanceProfile = createOrGetInstanceProfile(
name,
parent,
args.instanceRole,
args.instanceProfileName ?? nodeGroupOptions.instanceProfileName,
);
}
instanceRoles = pulumi.output([args.instanceRole]);
defaultInstanceRole = pulumi.output(args.instanceRole);
} else if (
args.createInstanceRole ||
(!args.skipDefaultNodeGroup && args.createInstanceRole === undefined)
) {
const instanceRole = new ServiceRole(
`${name}-instanceRole`,
{
service: pulumi.interpolate`ec2.${dnsSuffix}`,
managedPolicyArns: [
{
id: "arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy",
arn: pulumi.interpolate`arn:${partition}:iam::aws:policy/AmazonEKSWorkerNodePolicy`,
},
{
id: "arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy",
arn: pulumi.interpolate`arn:${partition}:iam::aws:policy/AmazonEKS_CNI_Policy`,
},
{
id: "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",
arn: pulumi.interpolate`arn:${partition}:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly`,
},
],
tags: args.tags,
},
{ parent, provider },
).resolvedRole;
defaultInstanceRole = instanceRole;
instanceRoles = pulumi.output([instanceRole]);
// Create a new policy for the role, if specified.
if (args.customInstanceRolePolicy) {
pulumi.log.warn(
"Option `customInstanceRolePolicy` has been deprecated. Please use `instanceRole` or `instanceRoles`. The role provided to either option should already include all required policies.",
eksCluster,
);
const customRolePolicy = new aws.iam.RolePolicy(
`${name}-EKSWorkerCustomPolicy`,
{
role: instanceRole,
policy: args.customInstanceRolePolicy,
},
{ parent, provider },
);
}
nodeGroupOptions.instanceProfile = createOrGetInstanceProfile(
name,
parent,
instanceRole,
args.instanceProfileName ?? nodeGroupOptions.instanceProfileName,
);
} else {
instanceRoles = pulumi.output([]);
}
let eksNodeAccess: k8s.core.v1.ConfigMap | undefined = undefined;
if (supportsConfigMap(args.authenticationMode)) {
// Create the aws-auth ConfigMap if the authentication mode supports it. This maps instance roles, regular IAM roles, and IAM users to
// Kubernetes RBAC users and groups.
const nodeAccessData = createAwsAuthData(
instanceRoles,
args.roleMappings,
args.userMappings,
);
eksNodeAccess = new k8s.core.v1.ConfigMap(
`${name}-nodeAccess`,
{
apiVersion: "v1",
immutable: false,
metadata: {
name: `aws-auth`,
namespace: "kube-system",
annotations: {
"pulumi.com/patchForce": "true",
},
},
data: nodeAccessData,
},
{ parent, provider: k8sProvider },
);
}
const createdAccessEntries: AccessEntry[] = [];
// Create the access entries if the authentication mode supports it.
let accessEntries: aws.eks.AccessEntry[] | undefined = undefined;
if (supportsAccessEntries(args.authenticationMode)) {