-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathvalidation.go
1711 lines (1490 loc) · 56.9 KB
/
validation.go
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
package v1alpha5
import (
"fmt"
"net"
"regexp"
"strconv"
"strings"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/arn"
ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
ekstypes "github.com/aws/aws-sdk-go-v2/service/eks/types"
"github.com/hashicorp/go-version"
"github.com/kris-nova/logger"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/validation"
kubeletapis "k8s.io/kubelet/pkg/apis"
"github.com/weaveworks/eksctl/pkg/utils"
instanceutils "github.com/weaveworks/eksctl/pkg/utils/instance"
"github.com/weaveworks/eksctl/pkg/utils/taints"
)
// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html
const (
MinThroughput = DefaultNodeVolumeThroughput
MaxThroughput = 1000
MinIO1Iops = DefaultNodeVolumeIO1IOPS
MaxIO1Iops = 64000
MinGP3Iops = DefaultNodeVolumeGP3IOPS
MaxGP3Iops = 16000
OneDay = 86400
)
var (
// ErrClusterEndpointNoAccess indicates the config prevents API access
ErrClusterEndpointNoAccess = errors.New("Kubernetes API access must have one of public or private clusterEndpoints enabled")
// ErrClusterEndpointPrivateOnly warns private-only access requires changes
// to AWS resource configuration in order to effectively use clients in the VPC
ErrClusterEndpointPrivateOnly = errors.New("warning, having public access disallowed will subsequently interfere with some " +
"features of eksctl. This will require running subsequent eksctl (and Kubernetes) " +
"commands/API calls from within the VPC. Running these in the VPC requires making " +
"updates to some AWS resources. See: " +
"https://docs.aws.amazon.com/eks/latest/userguide/cluster-endpoint.html " +
"for more details")
ErrPodIdentityAgentNotInstalled = func(suggestion string) error {
return fmt.Errorf("the %q addon must be installed to create pod identity associations; %s", PodIdentityAgentAddon, suggestion)
}
ErrUnsupportedInstanceTypes = func(instanceType, amiFamily, suggestion string) error {
return fmt.Errorf("%s instance types are not supported for %s; %s", instanceType, amiFamily, suggestion)
}
GPUDriversWarning = func(amiFamily string) string {
return fmt.Sprintf("%s does not ship with NVIDIA GPU drivers installed, hence won't support running GPU-accelerated workloads out of the box", amiFamily)
}
)
var (
SupportedAmazonLinuxImages = supportedAMIFamiliesForOS(IsAmazonLinuxImage)
SupportedUbuntuImages = supportedAMIFamiliesForOS(IsUbuntuImage)
)
// NOTE: we don't use k8s.io/apimachinery/pkg/util/sets here to keep API package free of dependencies
type nameSet map[string]struct{}
func (s nameSet) checkUnique(path, name string) (bool, error) {
if _, notUnique := s[name]; notUnique {
return false, fmt.Errorf("%s %q is not unique", path, name)
}
s[name] = struct{}{}
return true, nil
}
func setNonEmpty(field string) error {
return fmt.Errorf("%s must be set and non-empty", field)
}
// ValidateClusterConfig checks compatible fields of a given ClusterConfig
func ValidateClusterConfig(cfg *ClusterConfig) error {
if IsDisabled(cfg.IAM.WithOIDC) && len(cfg.IAM.ServiceAccounts) > 0 {
return fmt.Errorf("iam.withOIDC must be enabled explicitly for iam.serviceAccounts to be created")
}
saNames := nameSet{}
for i, sa := range cfg.IAM.ServiceAccounts {
path := fmt.Sprintf("iam.serviceAccounts[%d]", i)
if sa.Name == "" {
return fmt.Errorf("%s.name must be set", path)
}
if ok, err := saNames.checkUnique("<namespace>/<name> of "+path, sa.NameString()); !ok {
return err
}
if !sa.WellKnownPolicies.HasPolicy() && len(sa.AttachPolicyARNs) == 0 && sa.AttachPolicy == nil && sa.AttachRoleARN == "" {
return fmt.Errorf("%[1]s.wellKnownPolicies, %[1]s.attachPolicyARNs,%[1]s.attachRoleARN or %[1]s.attachPolicy must be set", path)
}
}
if err := cfg.validateKubernetesNetworkConfig(); err != nil {
return err
}
// names must be unique across both managed and unmanaged nodegroups
ngNames := nameSet{}
validateNg := func(ng *NodeGroupBase, path string) error {
if ng.Name == "" {
return fmt.Errorf("%s.name must be set", path)
}
if _, err := ngNames.checkUnique(path+".name", ng.Name); err != nil {
return err
}
if cfg.PrivateCluster.Enabled && !ng.PrivateNetworking {
return fmt.Errorf("%s.privateNetworking must be enabled for a fully-private cluster", path)
}
return nil
}
if err := validateIdentityProviders(cfg.IdentityProviders); err != nil {
return err
}
var ngOutpostARN string
for i, ng := range cfg.NodeGroups {
path := fmt.Sprintf("nodeGroups[%d]", i)
if err := validateNg(ng.NodeGroupBase, path); err != nil {
return err
}
if ng.OutpostARN != "" {
if ngOutpostARN != "" && ng.OutpostARN != ngOutpostARN {
return fmt.Errorf("cannot create nodegroups in two different Outposts; got Outpost ARN %q and %q", ngOutpostARN, ng.OutpostARN)
}
ngOutpostARN = ng.OutpostARN
}
}
for i, ng := range cfg.ManagedNodeGroups {
path := fmt.Sprintf("managedNodeGroups[%d]", i)
if err := validateNg(ng.NodeGroupBase, path); err != nil {
return err
}
}
if err := validateCloudWatchLogging(cfg); err != nil {
return err
}
if err := validateAvailabilityZones(cfg.AvailabilityZones); err != nil {
return err
}
if cfg.Outpost != nil {
if cfg.Outpost.ControlPlaneOutpostARN == "" {
return errors.New("outpost.controlPlaneOutpostARN is required for Outposts")
}
if err := validateOutpostARN(cfg.Outpost.ControlPlaneOutpostARN); err != nil {
return err
}
if cfg.AccessConfig.AuthenticationMode != ekstypes.AuthenticationModeConfigMap {
return fmt.Errorf("accessConfig.AuthenticationMode must be set to %s on Outposts", ekstypes.AuthenticationModeConfigMap)
}
if IsDisabled(cfg.AccessConfig.BootstrapClusterCreatorAdminPermissions) {
return fmt.Errorf("accessConfig.BootstrapClusterCreatorAdminPermissions can't be set to false on Outposts")
}
if cfg.IPv6Enabled() {
return errors.New("IPv6 is not supported on Outposts")
}
if len(cfg.Addons) > 0 {
return errors.New("Addons are not supported on Outposts")
}
if len(cfg.IdentityProviders) > 0 {
return errors.New("Identity Providers are not supported on Outposts")
}
if len(cfg.FargateProfiles) > 0 {
return errors.New("Fargate is not supported on Outposts")
}
if cfg.Karpenter != nil {
return errors.New("Karpenter is not supported on Outposts")
}
if cfg.SecretsEncryption != nil && cfg.SecretsEncryption.KeyARN != "" {
return errors.New("KMS encryption is not supported on Outposts")
}
const zonesErr = "cannot specify %s on Outposts; the AZ defaults to the Outpost AZ"
if len(cfg.AvailabilityZones) > 0 {
return fmt.Errorf(zonesErr, "availabilityZones")
}
if len(cfg.LocalZones) > 0 {
return fmt.Errorf(zonesErr, "localZones")
}
if cfg.GitOps != nil {
return errors.New("GitOps is not supported on Outposts")
}
if cfg.IAM != nil && IsEnabled(cfg.IAM.WithOIDC) {
return errors.New("iam.withOIDC is not supported on Outposts")
}
if cfg.VPC != nil {
if IsEnabled(cfg.VPC.AutoAllocateIPv6) {
return errors.New("autoAllocateIPv6 is not supported on Outposts")
}
if len(cfg.VPC.PublicAccessCIDRs) > 0 {
return errors.New("publicAccessCIDRs is not supported on Outposts")
}
}
} else if ngOutpostARN != "" && cfg.IsFullyPrivate() {
return errors.New("nodeGroup.outpostARN is not supported on a fully-private cluster (privateCluster.enabled)")
}
if err := cfg.ValidateVPCConfig(); err != nil {
return err
}
if err := ValidateSecretsEncryption(cfg); err != nil {
return err
}
if err := validateIAMIdentityMappings(cfg); err != nil {
return err
}
if err := validateAddonPodIdentityAssociations(cfg.Addons); err != nil {
return err
}
if len(cfg.AccessConfig.AccessEntries) > 0 {
switch cfg.AccessConfig.AuthenticationMode {
case ekstypes.AuthenticationModeConfigMap:
return fmt.Errorf("accessConfig.authenticationMode must be set to either %s or %s to use access entries",
ekstypes.AuthenticationModeApiAndConfigMap, ekstypes.AuthenticationModeApi)
}
if err := validateAccessEntries(cfg.AccessConfig.AccessEntries); err != nil {
return err
}
}
if err := validateKarpenterConfig(cfg); err != nil {
return fmt.Errorf("failed to validate Karpenter config: %w", err)
}
return nil
}
// ValidateClusterVersion validates the cluster version.
func ValidateClusterVersion(clusterConfig *ClusterConfig) error {
if clusterVersion := clusterConfig.Metadata.Version; clusterVersion != "" && clusterVersion != DefaultVersion && !IsSupportedVersion(clusterVersion) {
if IsDeprecatedVersion(clusterVersion) {
return fmt.Errorf("invalid version, %s is no longer supported, supported values: %s\nsee also: https://docs.aws.amazon.com/eks/latest/userguide/kubernetes-versions.html", clusterVersion, strings.Join(SupportedVersions(), ", "))
}
return fmt.Errorf("invalid version, supported values: %s", strings.Join(SupportedVersions(), ", "))
}
return nil
}
func validateKarpenterConfig(cfg *ClusterConfig) error {
if cfg.Karpenter == nil {
return nil
}
if cfg.Karpenter.Version == "" {
return errors.New("version field is required if installing Karpenter is enabled")
}
v, err := version.NewVersion(cfg.Karpenter.Version)
if err != nil {
return fmt.Errorf("failed to parse Karpenter version %q: %w", cfg.Karpenter.Version, err)
}
supportedVersion, err := version.NewVersion(supportedKarpenterVersion)
if err != nil {
return fmt.Errorf("failed to parse supported Karpenter version %s: %w", supportedKarpenterVersion, err)
}
if v.LessThan(supportedVersion) {
return fmt.Errorf("minimum supported version is %s", supportedKarpenterVersion)
}
if IsDisabled(cfg.IAM.WithOIDC) {
return errors.New("iam.withOIDC must be enabled with Karpenter")
}
return nil
}
func validateCloudWatchLogging(clusterConfig *ClusterConfig) error {
if !clusterConfig.HasClusterCloudWatchLogging() {
if clusterConfig.CloudWatch != nil &&
clusterConfig.CloudWatch.ClusterLogging != nil &&
clusterConfig.CloudWatch.ClusterLogging.LogRetentionInDays != 0 {
return errors.New("cannot set cloudWatch.clusterLogging.logRetentionInDays without enabling log types")
}
return nil
}
for i, logType := range clusterConfig.CloudWatch.ClusterLogging.EnableTypes {
isUnknown := true
for _, knownLogType := range SupportedCloudWatchClusterLogTypes() {
if logType == knownLogType {
isUnknown = false
}
}
if isUnknown {
return errors.Errorf("log type %q (cloudWatch.clusterLogging.enableTypes[%d]) is unknown", logType, i)
}
}
if logRetentionDays := clusterConfig.CloudWatch.ClusterLogging.LogRetentionInDays; logRetentionDays != 0 {
for _, v := range LogRetentionInDaysValues {
if v == logRetentionDays {
return nil
}
}
return errors.Errorf("invalid value %d for logRetentionInDays; supported values are %v", logRetentionDays, LogRetentionInDaysValues)
}
return nil
}
// ValidateVPCConfig validates the vpc setting if it is defined.
func (c *ClusterConfig) ValidateVPCConfig() error {
if c.VPC == nil {
return nil
}
if err := c.ValidatePrivateCluster(); err != nil {
return err
}
if err := c.ValidateClusterEndpointConfig(); err != nil {
return err
}
if len(c.VPC.ExtraCIDRs) > 0 {
cidrs, err := validateCIDRs(c.VPC.ExtraCIDRs)
if err != nil {
return err
}
c.VPC.ExtraCIDRs = cidrs
}
if len(c.VPC.PublicAccessCIDRs) > 0 {
cidrs, err := validateCIDRs(c.VPC.PublicAccessCIDRs)
if err != nil {
return err
}
c.VPC.PublicAccessCIDRs = cidrs
}
if len(c.VPC.ExtraIPv6CIDRs) > 0 {
if !c.IPv6Enabled() {
return fmt.Errorf("cannot specify vpc.extraIPv6CIDRs with an IPv4 cluster")
}
cidrs, err := validateCIDRs(c.VPC.ExtraIPv6CIDRs)
if err != nil {
return err
}
c.VPC.ExtraIPv6CIDRs = cidrs
}
if c.VPC.SecurityGroup != "" && len(c.VPC.ControlPlaneSecurityGroupIDs) > 0 {
return errors.New("only one of vpc.securityGroup and vpc.controlPlaneSecurityGroupIDs can be specified")
}
if (c.VPC.IPv6Cidr != "" || c.VPC.IPv6Pool != "") && !c.IPv6Enabled() {
return fmt.Errorf("Ipv6Cidr and Ipv6CidrPool are only supported when IPFamily is set to IPv6")
}
if c.IPv6Enabled() {
if IsEnabled(c.VPC.AutoAllocateIPv6) {
return fmt.Errorf("auto allocate ipv6 is not supported with IPv6")
}
if err := c.ipv6CidrsValid(); err != nil {
return err
}
if c.VPC.NAT != nil {
return fmt.Errorf("setting NAT is not supported with IPv6")
}
if len(c.LocalZones) > 0 {
return errors.New("localZones are not supported with IPv6")
}
}
// manageSharedNodeSecurityGroupRules cannot be disabled if using eksctl managed security groups
if c.VPC.SharedNodeSecurityGroup == "" && IsDisabled(c.VPC.ManageSharedNodeSecurityGroupRules) {
return errors.New("vpc.manageSharedNodeSecurityGroupRules must be enabled when using eksctl-managed security groups")
}
if c.VPC.HostnameType != "" {
if c.HasAnySubnets() {
return errors.New("vpc.hostnameType is not supported with a pre-existing VPC")
}
var hostnameType ec2types.HostnameType
found := false
for _, h := range hostnameType.Values() {
if h == ec2types.HostnameType(c.VPC.HostnameType) {
found = true
break
}
}
if !found {
return fmt.Errorf("invalid value %q for vpc.hostnameType; supported values are %v", c.VPC.HostnameType, hostnameType.Values())
}
}
if len(c.LocalZones) > 0 {
if c.VPC.ID != "" {
return errors.New("localZones are not supported with a pre-existing VPC")
}
if c.VPC.NAT != nil && c.VPC.NAT.Gateway != nil && *c.VPC.NAT.Gateway == ClusterHighlyAvailableNAT {
return fmt.Errorf("%s NAT gateway is not supported for localZones", ClusterHighlyAvailableNAT)
}
}
return nil
}
func (c *ClusterConfig) unsupportedVPCCNIAddonVersion() (bool, error) {
for _, addon := range c.Addons {
if addon.Name == VPCCNIAddon {
if addon.Version == "" {
return false, nil
}
if addon.Version == "latest" {
return false, nil
}
return versionLessThan(addon.Version, minimumVPCCNIVersionForIPv6)
}
}
return false, nil
}
func versionLessThan(v1, v2 string) (bool, error) {
v1Version, err := parseVersion(v1)
if err != nil {
return false, err
}
v2Version, err := parseVersion(v2)
if err != nil {
return false, err
}
return v1Version.LessThan(v2Version), nil
}
func parseVersion(v string) (*version.Version, error) {
version, err := version.NewVersion(v)
if err != nil {
return nil, fmt.Errorf("failed to parse version %q: %w", v, err)
}
return version, nil
}
func (c *ClusterConfig) ipv6CidrsValid() error {
if c.VPC.IPv6Cidr == "" && c.VPC.IPv6Pool == "" {
return nil
}
if c.VPC.IPv6Cidr != "" && c.VPC.IPv6Pool != "" {
if c.VPC.ID != "" {
return fmt.Errorf("cannot provide VPC.IPv6Cidr when using a pre-existing VPC.ID")
}
return nil
}
return fmt.Errorf("Ipv6Cidr and Ipv6Pool must both be configured to use a custom IPv6 CIDR and address pool")
}
// addonContainsManagedAddons finds managed addons in the config and returns those it couldn't find.
func (c *ClusterConfig) addonContainsManagedAddons(addons []string) []string {
var missing []string
for _, a := range addons {
found := false
for _, add := range c.Addons {
if strings.ToLower(add.Name) == a {
found = true
break
}
}
if !found {
missing = append(missing, a)
}
}
return missing
}
// ValidateClusterEndpointConfig checks the endpoint configuration for potential issues
func (c *ClusterConfig) ValidateClusterEndpointConfig() error {
if c.VPC.ClusterEndpoints != nil {
if !c.HasClusterEndpointAccess() {
return ErrClusterEndpointNoAccess
}
endpts := c.VPC.ClusterEndpoints
if noAccess(endpts) {
return ErrClusterEndpointNoAccess
}
}
return nil
}
// ValidatePrivateCluster validates the private cluster config
func (c *ClusterConfig) ValidatePrivateCluster() error {
if c.PrivateCluster.Enabled {
if c.VPC != nil && c.VPC.ID != "" && len(c.VPC.Subnets.Private) == 0 {
return errors.New("vpc.subnets.private must be specified in a fully-private cluster when a pre-existing VPC is supplied")
}
if additionalEndpoints := c.PrivateCluster.AdditionalEndpointServices; len(additionalEndpoints) > 0 {
if c.PrivateCluster.SkipEndpointCreation {
return errors.New("privateCluster.additionalEndpointServices cannot be set when privateCluster.skipEndpointCreation is true")
}
if err := ValidateAdditionalEndpointServices(additionalEndpoints); err != nil {
return fmt.Errorf("invalid value in privateCluster.additionalEndpointServices: %w", err)
}
}
if c.VPC != nil && c.VPC.ClusterEndpoints == nil {
c.VPC.ClusterEndpoints = &ClusterEndpoints{}
}
if len(c.LocalZones) > 0 {
return errors.New("localZones cannot be used in a fully-private cluster")
}
// public access is initially enabled to allow running operations that access the Kubernetes API
if !c.IsControlPlaneOnOutposts() {
c.VPC.ClusterEndpoints.PublicAccess = Enabled()
c.VPC.ClusterEndpoints.PrivateAccess = Enabled()
}
}
return nil
}
// validateKubernetesNetworkConfig validates the k8s network config
func (c *ClusterConfig) validateKubernetesNetworkConfig() error {
if c.KubernetesNetworkConfig == nil {
return nil
}
if c.KubernetesNetworkConfig.ServiceIPv4CIDR != "" {
if c.IPv6Enabled() {
return errors.New("service IPv4 CIDR is not supported with IPv6")
}
serviceIP := c.KubernetesNetworkConfig.ServiceIPv4CIDR
if _, _, err := net.ParseCIDR(serviceIP); serviceIP != "" && err != nil {
return errors.Wrap(err, "invalid IPv4 CIDR for kubernetesNetworkConfig.serviceIPv4CIDR")
}
}
switch strings.ToLower(c.KubernetesNetworkConfig.IPFamily) {
case strings.ToLower(IPV4Family), "":
case strings.ToLower(IPV6Family):
if missing := c.addonContainsManagedAddons([]string{VPCCNIAddon, CoreDNSAddon, KubeProxyAddon}); len(missing) != 0 {
return fmt.Errorf("the default core addons must be defined for IPv6; missing addon(s): %s", strings.Join(missing, ", "))
}
unsupportedVersion, err := c.unsupportedVPCCNIAddonVersion()
if err != nil {
return err
}
if unsupportedVersion {
return fmt.Errorf("%s version must be at least version %s for IPv6", VPCCNIAddon, minimumVPCCNIVersionForIPv6)
}
if c.IAM == nil || c.IAM != nil && IsDisabled(c.IAM.WithOIDC) {
return fmt.Errorf("oidc needs to be enabled if IPv6 is set")
}
if version, err := utils.CompareVersions(c.Metadata.Version, Version1_21); err != nil {
return fmt.Errorf("failed to convert %s cluster version to semver: %w", c.Metadata.Version, err)
} else if err == nil && version == -1 {
return fmt.Errorf("cluster version must be >= %s", Version1_21)
}
default:
return fmt.Errorf("invalid value %q for ipFamily; allowed are %s and %s", c.KubernetesNetworkConfig.IPFamily, IPV4Family, IPV6Family)
}
return nil
}
// NoAccess returns true if neither public are private cluster endpoint access is enabled and false otherwise
func noAccess(ces *ClusterEndpoints) bool {
return !(IsEnabled(ces.PublicAccess) || IsEnabled(ces.PrivateAccess))
}
// PrivateOnly returns true if public cluster endpoint access is disabled and private cluster endpoint access is enabled, and false otherwise
func PrivateOnly(ces *ClusterEndpoints) bool {
return !*ces.PublicAccess && *ces.PrivateAccess
}
func validateNodeGroupBase(np NodePool, path string, controlPlaneOnOutposts bool) error {
ng := np.BaseNodeGroup()
if ng.VolumeSize == nil {
errCantSet := func(field string) error {
return fmt.Errorf("%s.%s cannot be set without %s.volumeSize", path, field, path)
}
if IsSetAndNonEmptyString(ng.VolumeName) {
return errCantSet("volumeName")
}
if IsEnabled(ng.VolumeEncrypted) {
return errCantSet("volumeEncrypted")
}
if IsSetAndNonEmptyString(ng.VolumeKmsKeyID) {
return errCantSet("volumeKmsKeyID")
}
}
if err := validateVolumeOpts(ng, path, controlPlaneOnOutposts); err != nil {
return err
}
if ng.VolumeEncrypted == nil || IsDisabled(ng.VolumeEncrypted) {
if IsSetAndNonEmptyString(ng.VolumeKmsKeyID) {
return fmt.Errorf("%s.volumeKmsKeyID can not be set without %s.volumeEncrypted enabled explicitly", path, path)
}
}
if ng.MaxPodsPerNode < 0 {
return fmt.Errorf("%s.maxPodsPerNode cannot be negative", path)
}
if IsEnabled(ng.DisablePodIMDS) && ng.IAM != nil {
fmtFieldConflictErr := func(_ string) error {
return fmt.Errorf("%s.disablePodIMDS and %s.iam.withAddonPolicies cannot be set at the same time", path, path)
}
if err := validateNodeGroupIAMWithAddonPolicies(ng.IAM.WithAddonPolicies, fmtFieldConflictErr); err != nil {
return err
}
}
if len(ng.AvailabilityZones) > 0 && len(ng.Subnets) > 0 {
return fmt.Errorf("only one of %[1]s.subnets or %[1]s.availabilityZones should be set", path)
}
if ng.Placement != nil {
if ng.Placement.GroupName == "" {
return fmt.Errorf("%s.placement.groupName must be set and non-empty", path)
}
}
if IsEnabled(ng.EFAEnabled) {
if len(ng.AvailabilityZones) > 1 || len(ng.Subnets) > 1 {
return fmt.Errorf("%s.efaEnabled nodegroups must have only one subnet or one availability zone", path)
}
}
if ng.AMIFamily != "" {
if !isSupportedAMIFamily(ng.AMIFamily) {
if ng.AMIFamily == NodeImageFamilyWindowsServer20H2CoreContainer || ng.AMIFamily == NodeImageFamilyWindowsServer2004CoreContainer {
return fmt.Errorf("AMI Family %s is deprecated. For more information, head to the Amazon documentation on Windows AMIs (https://docs.aws.amazon.com/eks/latest/userguide/eks-optimized-windows-ami.html)", ng.AMIFamily)
}
return fmt.Errorf("AMI Family %s is not supported - use one of: %s", ng.AMIFamily, strings.Join(SupportedAMIFamilies(), ", "))
}
if controlPlaneOnOutposts && ng.AMIFamily != NodeImageFamilyAmazonLinux2 {
return fmt.Errorf("only %s is supported on local clusters", NodeImageFamilyAmazonLinux2)
}
}
if ng.SSH != nil {
if enableSSM := ng.SSH.EnableSSM; enableSSM != nil {
if !*enableSSM {
return errors.New("SSM agent is now built into EKS AMIs and cannot be disabled")
}
logger.Warning("SSM is now enabled by default; `ssh.enableSSM` is deprecated and will be removed in a future release")
}
}
instanceType := SelectInstanceType(np)
if ng.AMIFamily == NodeImageFamilyAmazonLinux2023 && instanceutils.IsNvidiaInstanceType(instanceType) {
return ErrUnsupportedInstanceTypes("GPU", NodeImageFamilyAmazonLinux2023,
fmt.Sprintf("EKS accelerated AMIs based on %s will be available at a later date", NodeImageFamilyAmazonLinux2023))
}
if ng.AMIFamily != NodeImageFamilyAmazonLinux2 && ng.AMIFamily != NodeImageFamilyBottlerocket && ng.AMIFamily != "" {
if instanceutils.IsNvidiaInstanceType(instanceType) {
logger.Warning(GPUDriversWarning(ng.AMIFamily))
}
if ng.InstanceSelector != nil && !ng.InstanceSelector.IsZero() &&
(ng.InstanceSelector.GPUs == nil || *ng.InstanceSelector.GPUs != 0) {
logger.Warning("instance selector may/will select GPU instance types, " + GPUDriversWarning(ng.AMIFamily))
}
}
if ng.AMIFamily != NodeImageFamilyAmazonLinux2 && ng.AMIFamily != "" {
// Only AL2 supports Inferentia hosts.
if instanceutils.IsInferentiaInstanceType(instanceType) {
return ErrUnsupportedInstanceTypes("Inferentia", ng.AMIFamily, fmt.Sprintf("please use %s instead", NodeImageFamilyAmazonLinux2))
}
// Only AL2 supports Trainium hosts.
if instanceutils.IsTrainiumInstanceType(instanceType) {
return ErrUnsupportedInstanceTypes("Trainium", ng.AMIFamily, fmt.Sprintf("please use %s instead", NodeImageFamilyAmazonLinux2))
}
}
if ng.CapacityReservation != nil {
if ng.CapacityReservation.CapacityReservationPreference != nil {
if ng.CapacityReservation.CapacityReservationTarget != nil {
return errors.New("only one of CapacityReservationPreference or CapacityReservationTarget may be specified at a time")
}
if *ng.CapacityReservation.CapacityReservationPreference != OpenCapacityReservation && *ng.CapacityReservation.CapacityReservationPreference != NoneCapacityReservation {
return fmt.Errorf(`accepted values include "open" and "none"; got "%s"`, *ng.CapacityReservation.CapacityReservationPreference)
}
}
if ng.CapacityReservation.CapacityReservationTarget != nil {
if ng.CapacityReservation.CapacityReservationTarget.CapacityReservationID != nil && ng.CapacityReservation.CapacityReservationTarget.CapacityReservationResourceGroupARN != nil {
return errors.New("only one of CapacityReservationID or CapacityReservationResourceGroupARN may be specified at a time")
}
}
}
return nil
}
func validateVolumeOpts(ng *NodeGroupBase, path string, controlPlaneOnOutposts bool) error {
if ng.VolumeType != nil {
volumeType := *ng.VolumeType
if ng.VolumeIOPS != nil && !(volumeType == NodeVolumeTypeIO1 || volumeType == NodeVolumeTypeGP3) {
return fmt.Errorf("%s.volumeIOPS is only supported for %s and %s volume types", path, NodeVolumeTypeIO1, NodeVolumeTypeGP3)
}
if volumeType == NodeVolumeTypeIO1 {
if ng.VolumeIOPS != nil && !(*ng.VolumeIOPS >= MinIO1Iops && *ng.VolumeIOPS <= MaxIO1Iops) {
return fmt.Errorf("value for %s.volumeIOPS must be within range %d-%d", path, MinIO1Iops, MaxIO1Iops)
}
}
if ng.VolumeThroughput != nil && volumeType != NodeVolumeTypeGP3 {
return fmt.Errorf("%s.volumeThroughput is only supported for %s volume type", path, NodeVolumeTypeGP3)
}
if controlPlaneOnOutposts && volumeType != NodeVolumeTypeGP2 {
return fmt.Errorf("cannot set %q for %s.volumeType; only %q volume types are supported on Outposts", volumeType, path, NodeVolumeTypeGP2)
}
}
if ng.VolumeType == nil || *ng.VolumeType == NodeVolumeTypeGP3 {
if ng.VolumeIOPS != nil && !(*ng.VolumeIOPS >= MinGP3Iops && *ng.VolumeIOPS <= MaxGP3Iops) {
return fmt.Errorf("value for %s.volumeIOPS must be within range %d-%d", path, MinGP3Iops, MaxGP3Iops)
}
if ng.VolumeThroughput != nil && !(*ng.VolumeThroughput >= MinThroughput && *ng.VolumeThroughput <= MaxThroughput) {
return fmt.Errorf("value for %s.volumeThroughput must be within range %d-%d", path, MinThroughput, MaxThroughput)
}
}
return nil
}
func validateIdentityProvider(idP IdentityProvider) error {
switch idP := (idP.Inner).(type) {
case *OIDCIdentityProvider:
if idP.Name == "" {
return setNonEmpty("name")
}
if idP.ClientID == "" {
return setNonEmpty("clientID")
}
if idP.IssuerURL == "" {
return setNonEmpty("issuerURL")
}
}
return nil
}
func validateIdentityProviders(idPs []IdentityProvider) error {
for k, idP := range idPs {
if err := validateIdentityProvider(idP); err != nil {
return errors.Wrapf(err, "identityProviders[%d] is invalid", k)
}
}
return nil
}
type unsupportedFieldError struct {
ng *NodeGroupBase
path string
field string
}
func (ue *unsupportedFieldError) Error() string {
return fmt.Sprintf("%s is not supported for %s nodegroups (path=%s.%s)", ue.field, ue.ng.AMIFamily, ue.path, ue.field)
}
// IsInvalidNameArg checks whether the name contains invalid characters
func IsInvalidNameArg(name string) bool {
re := regexp.MustCompile(`[^a-zA-Z0-9\-]+`)
return re.MatchString(name)
}
// errInvalidName error when invalid characters for a name is provided
func ErrInvalidName(name string) error {
return fmt.Errorf("validation for %s failed, name must satisfy regular expression pattern: [a-zA-Z][-a-zA-Z0-9]*", name)
}
func validateNodeGroupName(name string) error {
if name != "" && IsInvalidNameArg(name) {
return ErrInvalidName(name)
}
return nil
}
// ValidateNodeGroup checks compatible fields of a given nodegroup
func ValidateNodeGroup(i int, ng *NodeGroup, cfg *ClusterConfig) error {
normalizeAMIFamily(ng.BaseNodeGroup())
path := fmt.Sprintf("nodeGroups[%d]", i)
if err := validateNodeGroupBase(ng, path, cfg.IsControlPlaneOnOutposts()); err != nil {
return err
}
if err := validateNodeGroupName(ng.Name); err != nil {
return err
}
if ng.IAM != nil {
if err := validateNodeGroupIAM(ng.IAM, ng.IAM.InstanceProfileARN, "instanceProfileARN", path); err != nil {
return err
}
if err := validateNodeGroupIAM(ng.IAM, ng.IAM.InstanceRoleARN, "instanceRoleARN", path); err != nil {
return err
}
if attachPolicyARNs := ng.IAM.AttachPolicyARNs; len(attachPolicyARNs) > 0 {
for _, policyARN := range attachPolicyARNs {
if _, err := arn.Parse(policyARN); err != nil {
return errors.Wrapf(err, "invalid ARN %q in %s.iam.attachPolicyARNs", policyARN, path)
}
}
}
if err := validateDeprecatedIAMFields(ng.IAM); err != nil {
return err
}
}
if ng.AMI != "" && ng.AMIFamily == "" {
return errors.Errorf("when using a custom AMI, amiFamily needs to be explicitly set via config file or via --node-ami-family flag")
}
if ng.Bottlerocket != nil && ng.AMIFamily != NodeImageFamilyBottlerocket {
return fmt.Errorf(`bottlerocket config can only be used with amiFamily "Bottlerocket" but found "%s" (path=%s.bottlerocket)`,
ng.AMIFamily, path)
}
if ng.AMI != "" && ng.OverrideBootstrapCommand == nil &&
ng.AMIFamily != NodeImageFamilyAmazonLinux2023 &&
ng.AMIFamily != NodeImageFamilyBottlerocket &&
!IsWindowsImage(ng.AMIFamily) {
return errors.Errorf("%[1]s.overrideBootstrapCommand is required when using a custom AMI based on %s (%[1]s.ami)", path, ng.AMIFamily)
}
if err := validateTaints(ng.Taints); err != nil {
return err
}
if err := validateLabels(ng.Labels); err != nil {
return err
}
if ng.SSH != nil {
if err := validateNodeGroupSSH(ng.SSH); err != nil {
return err
}
}
fieldNotSupported := func(field string) error {
return &unsupportedFieldError{
ng: ng.NodeGroupBase,
path: path,
field: field,
}
}
if IsWindowsImage(ng.AMIFamily) {
if ng.KubeletExtraConfig != nil {
return fieldNotSupported("kubeletExtraConfig")
}
} else if ng.AMIFamily == NodeImageFamilyAmazonLinux2023 {
if ng.PreBootstrapCommands != nil {
return fieldNotSupported("preBootstrapCommands")
}
if ng.OverrideBootstrapCommand != nil {
return fieldNotSupported("overrideBootstrapCommand")
}
} else if ng.AMIFamily == NodeImageFamilyBottlerocket {
if ng.KubeletExtraConfig != nil {
return fieldNotSupported("kubeletExtraConfig")
}
if ng.PreBootstrapCommands != nil {
return fieldNotSupported("preBootstrapCommands")
}
if ng.OverrideBootstrapCommand != nil {
return fieldNotSupported("overrideBootstrapCommand")
}
if ng.Bottlerocket != nil && ng.Bottlerocket.Settings != nil {
if err := checkBottlerocketSettings(ng, path); err != nil {
return err
}
}
} else if err := validateNodeGroupKubeletExtraConfig(ng.KubeletExtraConfig); err != nil {
return err
}
if instanceutils.IsARMGPUInstanceType(SelectInstanceType(ng)) && ng.AMIFamily != NodeImageFamilyBottlerocket {
return fmt.Errorf("ARM GPU instance types are not supported for unmanaged nodegroups with AMIFamily %s", ng.AMIFamily)
}
if err := validateInstancesDistribution(ng); err != nil {
return err
}
if err := validateCPUCredits(ng); err != nil {
return err
}
if err := validateASGSuspendProcesses(ng); err != nil {
return err
}
if ng.ContainerRuntime != nil {
if ng.AMIFamily == NodeImageFamilyAmazonLinux2023 && *ng.ContainerRuntime != ContainerRuntimeContainerD {
return fmt.Errorf("only %s is supported for container runtime on %s nodes", ContainerRuntimeContainerD, NodeImageFamilyAmazonLinux2023)
}
if *ng.ContainerRuntime != ContainerRuntimeDockerD && *ng.ContainerRuntime != ContainerRuntimeContainerD && *ng.ContainerRuntime != ContainerRuntimeDockerForWindows {
return fmt.Errorf("only %s, %s and %s are supported for container runtime", ContainerRuntimeContainerD, ContainerRuntimeDockerD, ContainerRuntimeDockerForWindows)
}
if clusterVersion := cfg.Metadata.Version; clusterVersion != "" {
isDockershimDeprecated, err := utils.IsMinVersion(DockershimDeprecationVersion, clusterVersion)
if err != nil {
return err
}
if *ng.ContainerRuntime != ContainerRuntimeContainerD && isDockershimDeprecated {
return fmt.Errorf("only %s is supported for container runtime, starting with EKS version %s", ContainerRuntimeContainerD, Version1_24)
}
}
if ng.OverrideBootstrapCommand != nil {
return fmt.Errorf("overrideBootstrapCommand overwrites container runtime setting; please use --container-runtime in the bootsrap script instead")
}
}
if ng.MaxInstanceLifetime != nil {
if *ng.MaxInstanceLifetime < OneDay {
return fmt.Errorf("maximum instance lifetime must have a minimum value of 86,400 seconds (one day), but was: %d", *ng.MaxInstanceLifetime)
}
}
if len(ng.LocalZones) > 0 && len(ng.AvailabilityZones) > 0 {
return errors.New("cannot specify both localZones and availabilityZones")
}
if ng.OutpostARN != "" {
if err := validateOutpostARN(ng.OutpostARN); err != nil {
return err
}
if cfg.IsControlPlaneOnOutposts() && ng.OutpostARN != cfg.GetOutpost().ControlPlaneOutpostARN {
return fmt.Errorf("nodeGroup.outpostARN must either be empty or match the control plane's Outpost ARN (%q != %q)", ng.OutpostARN, cfg.GetOutpost().ControlPlaneOutpostARN)
}
}
if cfg.IsControlPlaneOnOutposts() || ng.OutpostARN != "" {
if ng.InstanceSelector != nil && !ng.InstanceSelector.IsZero() {
return errors.New("cannot specify instanceSelector for a nodegroup on Outposts")
}
const msg = "%s cannot be specified for a nodegroup on Outposts; the AZ defaults to the Outpost AZ"
if len(ng.AvailabilityZones) > 0 {
return fmt.Errorf(msg, "availabilityZones")
}
if len(ng.LocalZones) > 0 {
return fmt.Errorf(msg, "localZones")
}
}
return nil
}
func validateOutpostARN(val string) error {
parsed, err := arn.Parse(val)
if err != nil {
return fmt.Errorf("invalid Outpost ARN: %w", err)
}
if parsed.Service != "outposts" {
return fmt.Errorf("invalid Outpost ARN: %q", val)
}
return nil
}
// validateLabels uses proper Kubernetes label validation,
// it's designed to make sure users don't pass invalid or disallowed labels,
// which would prevent kubelets to startup properly
func validateLabels(labels map[string]string) error {
// compact version based on:
// - https://github.com/kubernetes/kubernetes/blob/v1.13.2/cmd/kubelet/app/options/options.go#L257-L267
// - https://github.com/kubernetes/kubernetes/blob/v1.13.2/pkg/kubelet/apis/well_known_labels.go
// we cannot import those packages because they break other dependencies
disallowedKubernetesLabels := []string{}
for label := range labels {
labelParts := strings.Split(label, "/")
if len(labelParts) > 2 {
return fmt.Errorf("node label key %q is of invalid format, can only use one '/' separator", label)
}