-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
template_functions.go
1124 lines (988 loc) · 36.3 KB
/
template_functions.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
/*
Copyright 2019 The Kubernetes Authors.
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.
*/
/******************************************************************************
Template Functions are what map functions in the models, to internal logic in
kops. This is the point where we connect static YAML configuration to dynamic
runtime values in memory.
When defining a new function:
- Build the new function here
- Define the new function in AddTo()
dest["MyNewFunction"] = MyNewFunction // <-- Function Pointer
******************************************************************************/
package cloudup
import (
"encoding/base64"
"encoding/json"
"fmt"
"net"
"os"
"path"
"sort"
"strconv"
"strings"
"text/template"
"github.com/Masterminds/sprig/v3"
"github.com/aws/aws-sdk-go/service/ec2"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/klog/v2"
kopsroot "k8s.io/kops"
kopscontrollerconfig "k8s.io/kops/cmd/kops-controller/pkg/config"
"k8s.io/kops/pkg/apis/kops"
apiModel "k8s.io/kops/pkg/apis/kops/model"
"k8s.io/kops/pkg/apis/kops/util"
"k8s.io/kops/pkg/apis/nodeup"
"k8s.io/kops/pkg/dns"
"k8s.io/kops/pkg/featureflag"
"k8s.io/kops/pkg/flagbuilder"
"k8s.io/kops/pkg/kubemanifest"
"k8s.io/kops/pkg/model"
"k8s.io/kops/pkg/model/components/kopscontroller"
"k8s.io/kops/pkg/model/iam"
"k8s.io/kops/pkg/resources/spotinst"
"k8s.io/kops/pkg/wellknownports"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
"k8s.io/kops/upup/pkg/fi/cloudup/azure"
"k8s.io/kops/upup/pkg/fi/cloudup/do"
"k8s.io/kops/upup/pkg/fi/cloudup/gce"
gcetpm "k8s.io/kops/upup/pkg/fi/cloudup/gce/tpm"
"k8s.io/kops/upup/pkg/fi/cloudup/hetzner"
"k8s.io/kops/upup/pkg/fi/cloudup/openstack"
"k8s.io/kops/upup/pkg/fi/cloudup/scaleway"
"k8s.io/kops/util/pkg/env"
"k8s.io/kops/util/pkg/maps"
"sigs.k8s.io/yaml"
)
// TemplateFunctions provides a collection of methods used throughout the templates
type TemplateFunctions struct {
model.KopsModelContext
cloud fi.Cloud
}
// AddTo defines the available functions we can use in our YAML models.
// If we are trying to get a new function implemented it MUST
// be defined here.
func (tf *TemplateFunctions) AddTo(dest template.FuncMap, secretStore fi.SecretStore) (err error) {
cluster := tf.Cluster
dest["ToJSON"] = tf.ToJSON
dest["ToYAML"] = tf.ToYAML
dest["KubeObjectToApplyYAML"] = kubemanifest.KubeObjectToApplyYAML
dest["SharedVPC"] = tf.SharedVPC
// Remember that we may be on a different arch from the target. Hard-code for now.
dest["replace"] = func(s, find, replace string) string {
return strings.Replace(s, find, replace, -1)
}
dest["joinHostPort"] = net.JoinHostPort
sprigTxtFuncMap := sprig.TxtFuncMap()
dest["nindent"] = sprigTxtFuncMap["nindent"]
dest["indent"] = sprigTxtFuncMap["indent"]
dest["contains"] = sprigTxtFuncMap["contains"]
dest["trimPrefix"] = sprigTxtFuncMap["trimPrefix"]
dest["semverCompare"] = sprigTxtFuncMap["semverCompare"]
dest["ternary"] = sprigTxtFuncMap["ternary"]
dest["join"] = sprigTxtFuncMap["join"]
dest["ClusterName"] = tf.ClusterName
dest["WithDefaultBool"] = func(v *bool, defaultValue bool) bool {
if v != nil {
return *v
}
return defaultValue
}
dest["GetCloudProvider"] = cluster.Spec.GetCloudProvider
dest["GetInstanceGroup"] = tf.GetInstanceGroup
dest["GetNodeInstanceGroups"] = tf.GetNodeInstanceGroups
dest["GetClusterAutoscalerNodeGroups"] = tf.GetClusterAutoscalerNodeGroups
dest["HasHighlyAvailableControlPlane"] = tf.HasHighlyAvailableControlPlane
dest["ControlPlaneControllerReplicas"] = tf.ControlPlaneControllerReplicas
dest["APIServerNodeRole"] = tf.APIServerNodeRole
dest["APIInternalName"] = tf.Cluster.APIInternalName
dest["CloudTags"] = tf.CloudTagsForInstanceGroup
dest["KubeDNS"] = func() *kops.KubeDNSConfig {
return cluster.Spec.KubeDNS
}
dest["GossipEnabled"] = func() bool {
if cluster.UsesLegacyGossip() {
return true
}
return false
}
dest["GossipName"] = func() bool {
if dns.IsGossipClusterName(cluster.Name) {
return true
}
return false
}
dest["NodeLocalDNSClusterIP"] = func() string {
if cluster.Spec.KubeProxy.ProxyMode == "ipvs" {
return cluster.Spec.KubeDNS.ServerIP
}
return "__PILLAR__CLUSTER__DNS__"
}
dest["NodeLocalDNSHealthCheck"] = func() string {
return fmt.Sprintf("%d", wellknownports.NodeLocalDNSHealthCheck)
}
dest["KopsControllerArgv"] = tf.KopsControllerArgv
dest["KopsControllerConfig"] = tf.KopsControllerConfig
kopscontroller.AddTemplateFunctions(cluster, dest)
dest["DnsControllerArgv"] = tf.DNSControllerArgv
dest["ExternalDnsArgv"] = tf.ExternalDNSArgv
dest["CloudControllerConfigArgv"] = tf.CloudControllerConfigArgv
// TODO: Only for GCE?
dest["EncodeGCELabel"] = gce.EncodeGCELabel
dest["Region"] = func() string {
return tf.Region
}
// will return openstack external ccm image location for current kubernetes version
dest["OpenStackCCMTag"] = tf.OpenStackCCMTag
dest["OpenStackCSITag"] = tf.OpenStackCSITag
dest["DNSControllerEnvs"] = tf.DNSControllerEnvs
dest["ProxyEnv"] = tf.ProxyEnv
dest["KopsSystemEnv"] = tf.KopsSystemEnv
dest["DO_TOKEN"] = func() string {
return os.Getenv("DIGITALOCEAN_ACCESS_TOKEN")
}
dest["HCLOUD_TOKEN"] = func() string {
return os.Getenv("HCLOUD_TOKEN")
}
dest["HCLOUD_NETWORK"] = func() string {
if cluster.Spec.Networking.NetworkID != "" {
return cluster.Spec.Networking.NetworkID
}
return cluster.Name
}
dest["OPENSTACK_CONF"] = func() string {
lines := openstack.MakeCloudConfig(cluster.Spec.CloudProvider.Openstack)
return "[global]\n" + strings.Join(lines, "\n") + "\n"
}
dest["SCW_ACCESS_KEY"] = func() string {
profile, err := scaleway.CreateValidScalewayProfile()
if err != nil {
return ""
}
return fi.ValueOf(profile.AccessKey)
}
dest["SCW_SECRET_KEY"] = func() string {
profile, err := scaleway.CreateValidScalewayProfile()
if err != nil {
return ""
}
return fi.ValueOf(profile.SecretKey)
}
dest["SCW_DEFAULT_PROJECT_ID"] = func() string {
profile, err := scaleway.CreateValidScalewayProfile()
if err != nil {
return ""
}
return fi.ValueOf(profile.DefaultProjectID)
}
dest["SCW_DEFAULT_REGION"] = func() string {
return tf.cloud.Region()
}
dest["SCW_DEFAULT_ZONE"] = func() string {
scwCloud := tf.cloud.(scaleway.ScwCloud)
return scwCloud.Zone()
}
if featureflag.Spotinst.Enabled() {
if creds, err := spotinst.LoadCredentials(); err == nil {
dest["SpotinstToken"] = func() string { return creds.Token }
dest["SpotinstAccount"] = func() string { return creds.Account }
dest["SpotinstTokenBase64"] = func() string { return base64.StdEncoding.EncodeToString([]byte(creds.Token)) }
dest["SpotinstAccountBase64"] = func() string { return base64.StdEncoding.EncodeToString([]byte(creds.Account)) }
}
}
if cluster.Spec.Networking.AmazonVPC != nil {
c := cluster.Spec.Networking.AmazonVPC
dest["AmazonVpcEnvVars"] = func() map[string]string {
envVars := map[string]string{
// Use defaults from the official AWS VPC CNI Helm chart:
// https://github.com/aws/amazon-vpc-cni-k8s/blob/master/charts/aws-vpc-cni/values.yaml
"ADDITIONAL_ENI_TAGS": "{}",
"AWS_VPC_CNI_NODE_PORT_SUPPORT": "true",
"AWS_VPC_ENI_MTU": "9001",
"AWS_VPC_K8S_CNI_CONFIGURE_RPFILTER": "false",
"AWS_VPC_K8S_CNI_CUSTOM_NETWORK_CFG": "false",
"AWS_VPC_K8S_CNI_EXTERNALSNAT": "false",
"AWS_VPC_K8S_CNI_LOG_FILE": "/host/var/log/aws-routed-eni/ipamd.log",
"AWS_VPC_K8S_CNI_LOGLEVEL": "DEBUG",
"AWS_VPC_K8S_CNI_RANDOMIZESNAT": "prng",
"AWS_VPC_K8S_CNI_VETHPREFIX": "eni",
"AWS_VPC_K8S_PLUGIN_LOG_FILE": "/var/log/aws-routed-eni/plugin.log",
"AWS_VPC_K8S_PLUGIN_LOG_LEVEL": "DEBUG",
"DISABLE_INTROSPECTION": "false",
"DISABLE_METRICS": "false",
"ENABLE_POD_ENI": "false",
"ENABLE_PREFIX_DELEGATION": "false",
"WARM_ENI_TARGET": "1",
"WARM_PREFIX_TARGET": "1",
"DISABLE_NETWORK_RESOURCE_PROVISIONING": "false",
}
for _, e := range c.Env {
envVars[e.Name] = e.Value
}
envVars["ENABLE_IPv4"] = strconv.FormatBool(!cluster.Spec.IsIPv6Only())
envVars["ENABLE_IPv6"] = strconv.FormatBool(cluster.Spec.IsIPv6Only())
if cluster.Spec.IsIPv6Only() {
envVars["ENABLE_PREFIX_DELEGATION"] = "true"
envVars["WARM_PREFIX_TARGET"] = "1"
}
envVars["ADDITIONAL_ENI_TAGS"] = fmt.Sprintf(
"{\\\"KubernetesCluster\\\":\\\"%s\\\",\\\"kubernetes.io/cluster/%s\\\":\\\"owned\\\"}",
tf.ClusterName(),
tf.ClusterName(),
)
return envVars
}
}
if cluster.Spec.Networking.Calico != nil {
c := cluster.Spec.Networking.Calico
dest["CalicoIPv4PoolIPIPMode"] = func() string {
if c.EncapsulationMode != "ipip" {
return "Never"
}
if c.IPIPMode != "" {
return c.IPIPMode
}
if cluster.Spec.GetCloudProvider() == kops.CloudProviderOpenstack {
return "Always"
}
return "CrossSubnet"
}
dest["CalicoIPv4PoolVXLANMode"] = func() string {
if c.EncapsulationMode != "vxlan" {
return "Never"
}
if c.VXLANMode != "" {
return c.VXLANMode
}
return "CrossSubnet"
}
}
if cluster.Spec.Networking.Cilium != nil {
ciliumsecretString := ""
ciliumsecret, _ := secretStore.Secret("ciliumpassword")
if ciliumsecret != nil {
ciliumsecretString, err = ciliumsecret.AsString()
if err != nil {
return err
}
klog.V(4).Info("Cilium secret function successfully registered")
}
dest["CiliumSecret"] = func() string { return ciliumsecretString }
}
if cluster.Spec.Networking.Flannel != nil {
flannelBackendType := cluster.Spec.Networking.Flannel.Backend
if flannelBackendType == "" {
klog.Warningf("Defaulting flannel backend to udp (not a recommended configuration)")
flannelBackendType = "udp"
}
dest["FlannelBackendType"] = func() string { return flannelBackendType }
}
dest["CloudLabels"] = func() string {
labels := []string{
fmt.Sprintf("KubernetesCluster=%s", cluster.ObjectMeta.Name),
}
for n, v := range cluster.Spec.CloudLabels {
labels = append(labels, fmt.Sprintf("%s=%s", n, v))
}
// ensure stable sorting of tags
sort.Strings(labels)
return strings.Join(labels, ",")
}
dest["IsIPv6Only"] = tf.IsIPv6Only
dest["UseServiceAccountExternalPermissions"] = tf.UseServiceAccountExternalPermissions
if cluster.Spec.ClusterAutoscaler != nil {
dest["ClusterAutoscalerPriorities"] = func() string {
priorities := make(map[string][]string)
if cluster.Spec.ClusterAutoscaler.CustomPriorityExpanderConfig != nil {
priorities = cluster.Spec.ClusterAutoscaler.CustomPriorityExpanderConfig
} else {
for name, spec := range tf.GetNodeInstanceGroups() {
if spec.Autoscale != nil {
priorities[strconv.Itoa(int(spec.AutoscalePriority))] = append(priorities[strconv.Itoa(int(spec.AutoscalePriority))], fmt.Sprintf("%s.%s", name, tf.ClusterName()))
}
}
}
var prioritiesStr []string
for _, prio := range maps.SortedKeys(priorities) {
prioritiesStr = append(prioritiesStr, fmt.Sprintf("%s:", prio))
for _, value := range priorities[prio] {
prioritiesStr = append(prioritiesStr, fmt.Sprintf("- %s", value))
}
}
return strings.Join(prioritiesStr, "\n")
}
dest["CreateClusterAutoscalerPriorityConfig"] = func() bool {
return fi.ValueOf(cluster.Spec.ClusterAutoscaler.CreatePriorityExpenderConfig)
}
}
if cluster.Spec.CloudProvider.AWS != nil && cluster.Spec.CloudProvider.AWS.NodeTerminationHandler != nil {
dest["DefaultQueueName"] = func() string {
s := strings.Replace(tf.ClusterName(), ".", "-", -1)
domain := ".amazonaws.com/"
if strings.Contains(tf.Region, "cn-") {
domain = ".amazonaws.com.cn/"
}
url := "https://sqs." + tf.Region + domain + tf.AWSAccountID + "/" + s + "-nth"
return url
}
dest["EnableSQSTerminationDraining"] = func() bool { return cluster.Spec.CloudProvider.AWS.NodeTerminationHandler.IsQueueMode() }
}
dest["ArchitectureOfAMI"] = tf.architectureOfAMI
dest["ParseTaint"] = util.ParseTaint
dest["UsesInstanceIDForNodeName"] = func() bool {
return nodeup.UsesInstanceIDForNodeName(tf.Cluster)
}
dest["KarpenterEnabled"] = func() bool {
return cluster.Spec.Karpenter != nil && cluster.Spec.Karpenter.Enabled
}
dest["KarpenterInstanceTypes"] = func(ig kops.InstanceGroupSpec) ([]string, error) {
return karpenterInstanceTypes(tf.cloud.(awsup.AWSCloud), ig)
}
dest["PodIdentityWebhookConfigMapData"] = tf.podIdentityWebhookConfigMapData
dest["HasSnapshotController"] = func() bool {
sc := cluster.Spec.SnapshotController
return sc != nil && fi.ValueOf(sc.Enabled)
}
dest["IsKubernetesGTE"] = tf.IsKubernetesGTE
dest["IsKubernetesLT"] = tf.IsKubernetesLT
dest["KopsFeatureEnabled"] = tf.kopsFeatureEnabled
dest["KopsVersion"] = func() string { return kopsroot.KOPS_RELEASE_VERSION }
dest["ContainerdSELinuxEnabled"] = func() bool {
if cluster.Spec.Containerd != nil {
return cluster.Spec.Containerd.SeLinuxEnabled
}
return false
}
return nil
}
// ToJSON returns a json representation of the struct or on error an empty string
func (tf *TemplateFunctions) ToJSON(data interface{}) string {
encoded, err := json.Marshal(data)
if err != nil {
return ""
}
return string(encoded)
}
// ToYAML returns a yaml representation of the struct or on error an empty string
func (tf *TemplateFunctions) ToYAML(data interface{}) string {
encoded, err := yaml.Marshal(data)
if err != nil {
return ""
}
return string(encoded)
}
// SharedVPC is a simple helper function which makes the templates for a shared VPC clearer
func (tf *TemplateFunctions) SharedVPC() bool {
return tf.Cluster.SharedVPC()
}
// GetInstanceGroup returns the instance group with the specified name
func (tf *TemplateFunctions) GetInstanceGroup(name string) (*kops.InstanceGroup, error) {
ig := tf.KopsModelContext.FindInstanceGroup(name)
if ig == nil {
return nil, fmt.Errorf("InstanceGroup %q not found", name)
}
return ig, nil
}
// ControlPlaneControllerReplicas returns the amount of replicas for a controllers that should run in the cluster.
// deployOnWorkersIfExternalPermissons indicates if a controller can run on worker nodes when external IAM permissions is enabled for the cluster.
func (tf *TemplateFunctions) ControlPlaneControllerReplicas(deployOnWorkersIfExternalPermissions bool) int {
// Check if we are running on worker nodes
if deployOnWorkersIfExternalPermissions && tf.Cluster.Spec.IAM != nil && fi.ValueOf(tf.Cluster.Spec.IAM.UseServiceAccountExternalPermissions) {
// If we only have one control plane node, we still only run one instance,
// because most controllers still need a lease from the control plane,
// so we can't get higher availability by running multiple instances
// (though we would get faster time-to-recovery)
//
// This also supports running with one control-plane node and one worker node,
// and we may have spreading constraints that prevent both pods running on
// the same worker node. Issue #15852
if tf.HasHighlyAvailableControlPlane() {
return 2
}
return 1
}
// If the cluster has a highly available control plane, we should run two instances of the controller,
// otherwise we run one 1.
if tf.HasHighlyAvailableControlPlane() {
return 2
}
return 1
}
func (tf *TemplateFunctions) APIServerNodeRole() string {
if featureflag.APIServerNodes.Enabled() {
return "node-role.kubernetes.io/api-server"
} else if tf.Cluster.IsKubernetesGTE("1.24") {
return "node-role.kubernetes.io/control-plane"
}
return "node-role.kubernetes.io/master"
}
// HasHighlyAvailableControlPlane returns true of the cluster has more than one control plane node. False otherwise.
func (tf *TemplateFunctions) HasHighlyAvailableControlPlane() bool {
cp := 0
for _, ig := range tf.InstanceGroups {
if ig.Spec.Role == kops.InstanceGroupRoleControlPlane {
cp++
if cp > 1 {
return true
}
}
}
return false
}
// CloudControllerConfigArgv returns the args to external cloud controller
func (tf *TemplateFunctions) CloudControllerConfigArgv() ([]string, error) {
cluster := tf.Cluster
if cluster.Spec.ExternalCloudControllerManager == nil {
return nil, fmt.Errorf("ExternalCloudControllerManager is nil")
}
argv, err := flagbuilder.BuildFlagsList(cluster.Spec.ExternalCloudControllerManager)
if err != nil {
return nil, err
}
// default verbosity to 2
if cluster.Spec.ExternalCloudControllerManager.LogLevel == 0 {
argv = append(argv, "--v=2")
}
// take the cloud provider value from clusterSpec if unset
if cluster.Spec.ExternalCloudControllerManager.CloudProvider == "" {
if cluster.Spec.GetCloudProvider() != "" {
argv = append(argv, fmt.Sprintf("--cloud-provider=%s", cluster.Spec.GetCloudProvider()))
} else {
return nil, fmt.Errorf("Cloud Provider is not set")
}
}
// default use-service-account-credentials to true
if cluster.Spec.ExternalCloudControllerManager.UseServiceAccountCredentials == nil {
argv = append(argv, fmt.Sprintf("--use-service-account-credentials=%t", true))
}
if cluster.Spec.GetCloudProvider() != kops.CloudProviderHetzner {
argv = append(argv, "--cloud-config=/etc/kubernetes/cloud.config")
}
return argv, nil
}
// DNSControllerArgv returns the args to the DNS controller
func (tf *TemplateFunctions) DNSControllerArgv() ([]string, error) {
cluster := tf.Cluster
var argv []string
// @check if the dns controller has custom configuration
if cluster.Spec.ExternalDNS == nil {
argv = append(argv, []string{"--watch-ingress=false"}...)
klog.V(4).Infof("watch-ingress=false set on dns-controller")
} else {
// @check if the watch ingress is set
var watchIngress bool
if cluster.Spec.ExternalDNS.WatchIngress != nil {
watchIngress = fi.ValueOf(cluster.Spec.ExternalDNS.WatchIngress)
}
if watchIngress {
klog.Warningln("--watch-ingress=true set on dns-controller")
klog.Warningln("this may cause problems with previously defined services: https://github.com/kubernetes/kops/issues/2496")
}
argv = append(argv, fmt.Sprintf("--watch-ingress=%t", watchIngress))
if cluster.Spec.ExternalDNS.WatchNamespace != "" {
argv = append(argv, fmt.Sprintf("--watch-namespace=%s", cluster.Spec.ExternalDNS.WatchNamespace))
}
}
if cluster.UsesLegacyGossip() {
argv = append(argv, "--dns=gossip")
// Configuration specifically for the DNS controller gossip
if cluster.Spec.DNSControllerGossipConfig != nil {
if cluster.Spec.DNSControllerGossipConfig.Protocol != nil {
argv = append(argv, "--gossip-protocol="+*cluster.Spec.DNSControllerGossipConfig.Protocol)
}
if cluster.Spec.DNSControllerGossipConfig.Listen != nil {
argv = append(argv, "--gossip-listen="+*cluster.Spec.DNSControllerGossipConfig.Listen)
}
if cluster.Spec.DNSControllerGossipConfig.Secret != nil {
argv = append(argv, "--gossip-secret="+*cluster.Spec.DNSControllerGossipConfig.Secret)
}
if cluster.Spec.DNSControllerGossipConfig.Seed != nil {
argv = append(argv, "--gossip-seed="+*cluster.Spec.DNSControllerGossipConfig.Seed)
} else {
argv = append(argv, fmt.Sprintf("--gossip-seed=127.0.0.1:%d", wellknownports.ProtokubeGossipWeaveMesh))
}
if cluster.Spec.DNSControllerGossipConfig.Secondary != nil {
if cluster.Spec.DNSControllerGossipConfig.Secondary.Protocol != nil {
argv = append(argv, "--gossip-protocol-secondary="+*cluster.Spec.DNSControllerGossipConfig.Secondary.Protocol)
}
if cluster.Spec.DNSControllerGossipConfig.Secondary.Listen != nil {
argv = append(argv, "--gossip-listen-secondary="+*cluster.Spec.DNSControllerGossipConfig.Secondary.Listen)
}
if cluster.Spec.DNSControllerGossipConfig.Secondary.Secret != nil {
argv = append(argv, "--gossip-secret-secondary="+*cluster.Spec.DNSControllerGossipConfig.Secondary.Secret)
}
if cluster.Spec.DNSControllerGossipConfig.Secondary.Seed != nil {
argv = append(argv, "--gossip-seed-secondary="+*cluster.Spec.DNSControllerGossipConfig.Secondary.Seed)
} else {
argv = append(argv, fmt.Sprintf("--gossip-seed-secondary=127.0.0.1:%d", wellknownports.ProtokubeGossipMemberlist))
}
}
} else {
// Default to primary mesh and secondary memberlist
argv = append(argv, fmt.Sprintf("--gossip-seed=127.0.0.1:%d", wellknownports.ProtokubeGossipWeaveMesh))
argv = append(argv, "--gossip-protocol-secondary=memberlist")
argv = append(argv, fmt.Sprintf("--gossip-listen-secondary=0.0.0.0:%d", wellknownports.DNSControllerGossipMemberlist))
argv = append(argv, fmt.Sprintf("--gossip-seed-secondary=127.0.0.1:%d", wellknownports.ProtokubeGossipMemberlist))
}
} else {
switch cluster.Spec.GetCloudProvider() {
case kops.CloudProviderAWS:
if strings.HasPrefix(os.Getenv("AWS_REGION"), "cn-") {
argv = append(argv, "--dns=gossip")
} else {
argv = append(argv, "--dns=aws-route53")
}
case kops.CloudProviderGCE:
argv = append(argv, "--dns=google-clouddns")
case kops.CloudProviderDO:
argv = append(argv, "--dns=digitalocean")
case kops.CloudProviderOpenstack:
argv = append(argv, "--dns=openstack-designate")
case kops.CloudProviderScaleway:
argv = append(argv, "--dns=scaleway")
default:
return nil, fmt.Errorf("unhandled cloudprovider %q", cluster.Spec.GetCloudProvider())
}
}
zone := cluster.Spec.DNSZone
if zone != "" {
if strings.Contains(zone, ".") {
// match by name
argv = append(argv, "--zone="+zone)
} else {
// match by id
argv = append(argv, "--zone=*/"+zone)
}
}
if cluster.Spec.IsIPv6Only() {
argv = append(argv, "--internal-ipv6")
} else {
argv = append(argv, "--internal-ipv4")
}
// permit wildcard updates
argv = append(argv, "--zone=*/*")
// Verbose, but not crazy logging
argv = append(argv, "-v=2")
return argv, nil
}
// KopsControllerConfig returns the yaml configuration for kops-controller
func (tf *TemplateFunctions) KopsControllerConfig() (string, error) {
cluster := tf.Cluster
config := &kopscontrollerconfig.Options{
ClusterName: cluster.Name,
Cloud: string(cluster.Spec.GetCloudProvider()),
ConfigBase: cluster.Spec.ConfigStore.Base,
SecretStore: cluster.Spec.ConfigStore.Secrets,
}
if featureflag.CacheNodeidentityInfo.Enabled() {
config.CacheNodeidentityInfo = true
}
{
certNames := []string{"kubelet", "kubelet-server"}
signingCAs := []string{fi.CertificateIDCA}
if apiModel.UseCiliumEtcd(cluster) {
certNames = append(certNames, "etcd-client-cilium")
signingCAs = append(signingCAs, "etcd-clients-ca-cilium")
}
if cluster.Spec.KubeProxy.Enabled == nil || *cluster.Spec.KubeProxy.Enabled {
certNames = append(certNames, "kube-proxy")
}
if cluster.Spec.Networking.KubeRouter != nil {
certNames = append(certNames, "kube-router")
}
pkiDir := "/etc/kubernetes/kops-controller/pki"
config.Server = &kopscontrollerconfig.ServerOptions{
Listen: fmt.Sprintf(":%d", wellknownports.KopsControllerPort),
ServerCertificatePath: path.Join(pkiDir, "kops-controller.crt"),
ServerKeyPath: path.Join(pkiDir, "kops-controller.key"),
CABasePath: pkiDir,
SigningCAs: signingCAs,
CertNames: certNames,
}
switch cluster.Spec.GetCloudProvider() {
case kops.CloudProviderAWS:
nodesRoles := sets.String{}
for _, ig := range tf.InstanceGroups {
if ig.Spec.Role == kops.InstanceGroupRoleNode || ig.Spec.Role == kops.InstanceGroupRoleAPIServer {
profile, err := tf.LinkToIAMInstanceProfile(ig)
if err != nil {
return "", fmt.Errorf("getting profile for ig %s: %v", ig.Name, err)
}
// The IAM Instance Profile has not been created at this point if it is not specified.
// Because the IAM Instance Profile and the IAM Role are created in IAMModelBuilder tasks.
// Therefore, the IAM Role associated with IAM Instance Profile is acquired only when it is not specified.
if ig.Spec.IAM != nil && ig.Spec.IAM.Profile != nil {
c := tf.cloud.(awsup.AWSCloud)
roles, err := awsup.GetRolesInInstanceProfile(c, *profile.Name)
if err != nil {
return "", fmt.Errorf("getting role from profile %s: %v", *profile.Name, err)
}
nodesRoles.Insert(roles...)
} else {
// When the IAM Instance Profile is not specified, IAM Instance Profile is created by kOps.
// In this case, the IAM Instance Profile name and IAM Role name are same.
// So there is no problem even if IAM Instance Profile name is inserted as role name in nodesRoles.
nodesRoles.Insert(*profile.Name)
}
}
}
config.Server.Provider.AWS = &awsup.AWSVerifierOptions{
NodesRoles: nodesRoles.List(),
Region: tf.Region,
}
if cluster.Spec.ExternalCloudControllerManager != nil {
config.Server.UseInstanceIDForNodeName = true
}
case kops.CloudProviderGCE:
c := tf.cloud.(gce.GCECloud)
config.Server.Provider.GCE = &gcetpm.TPMVerifierOptions{
ProjectID: c.Project(),
ClusterName: tf.ClusterName(),
Region: tf.Region,
MaxTimeSkew: 300,
}
case kops.CloudProviderHetzner:
config.Server.Provider.Hetzner = &hetzner.HetznerVerifierOptions{}
case kops.CloudProviderOpenstack:
config.Server.Provider.OpenStack = &openstack.OpenStackVerifierOptions{}
case kops.CloudProviderDO:
config.Server.Provider.DigitalOcean = &do.DigitalOceanVerifierOptions{}
case kops.CloudProviderScaleway:
config.Server.Provider.Scaleway = &scaleway.ScalewayVerifierOptions{}
case kops.CloudProviderAzure:
config.Server.Provider.Azure = &azure.AzureVerifierOptions{
ClusterName: tf.ClusterName(),
}
default:
return "", fmt.Errorf("unsupported cloud provider %s", cluster.Spec.GetCloudProvider())
}
}
if cluster.Spec.IsKopsControllerIPAM() {
config.EnableCloudIPAM = true
}
if cluster.UsesLegacyGossip() {
config.Discovery = &kopscontrollerconfig.DiscoveryOptions{
Enabled: true,
}
}
// To avoid indentation problems, we marshal as json. json is a subset of yaml
b, err := json.Marshal(config)
if err != nil {
return "", fmt.Errorf("failed to serialize kops-controller config: %v", err)
}
return string(b), nil
}
// KopsControllerArgv returns the args to kops-controller
func (tf *TemplateFunctions) KopsControllerArgv() ([]string, error) {
var argv []string
// Verbose, but not excessive logging
argv = append(argv, "--v=2")
argv = append(argv, "--conf=/etc/kubernetes/kops-controller/config/config.yaml")
return argv, nil
}
func (tf *TemplateFunctions) ExternalDNSArgv() ([]string, error) {
cluster := tf.Cluster
externalDNS := tf.Cluster.Spec.ExternalDNS
var argv []string
cloudProvider := cluster.Spec.GetCloudProvider()
switch cloudProvider {
case kops.CloudProviderAWS:
argv = append(argv, "--provider=aws")
case kops.CloudProviderGCE:
project := cluster.Spec.CloudProvider.GCE.Project
argv = append(argv, "--provider=google")
argv = append(argv, "--google-project="+project)
default:
return nil, fmt.Errorf("unhandled cloudprovider %q", cluster.Spec.GetCloudProvider())
}
argv = append(argv, "--events")
if externalDNS.WatchIngress == nil || *externalDNS.WatchIngress {
argv = append(argv, "--source=ingress")
}
argv = append(argv, "--source=pod")
argv = append(argv, "--source=service")
argv = append(argv, "--compatibility=kops-dns-controller")
argv = append(argv, "--registry=txt")
argv = append(argv, "--txt-owner-id=kops-"+tf.ClusterName())
argv = append(argv, "--zone-id-filter="+tf.Cluster.Spec.DNSZone)
if externalDNS.WatchNamespace != "" {
argv = append(argv, "--namespace="+externalDNS.WatchNamespace)
}
return argv, nil
}
func (tf *TemplateFunctions) DNSControllerEnvs() map[string]string {
if tf.Cluster.Spec.GetCloudProvider() != kops.CloudProviderOpenstack {
return nil
}
envs := env.BuildSystemComponentEnvVars(&tf.Cluster.Spec)
out := make(map[string]string)
for k, v := range envs {
if strings.HasPrefix(k, "OS_") {
out[k] = v
}
}
return out
}
func (tf *TemplateFunctions) ProxyEnv() map[string]string {
cluster := tf.Cluster
envs := map[string]string{}
proxies := cluster.Spec.Networking.EgressProxy
if proxies == nil {
return envs
}
httpProxy := proxies.HTTPProxy
if httpProxy.Host != "" {
var portSuffix string
if httpProxy.Port != 0 {
portSuffix = ":" + strconv.Itoa(httpProxy.Port)
} else {
portSuffix = ""
}
url := "http://" + httpProxy.Host + portSuffix
envs["http_proxy"] = url
envs["https_proxy"] = url
}
if proxies.ProxyExcludes != "" {
envs["no_proxy"] = proxies.ProxyExcludes
envs["NO_PROXY"] = proxies.ProxyExcludes
}
return envs
}
// KopsSystemEnv builds the env vars for a system component
func (tf *TemplateFunctions) KopsSystemEnv() []corev1.EnvVar {
envMap := env.BuildSystemComponentEnvVars(&tf.Cluster.Spec)
return envMap.ToEnvVars()
}
// OpenStackCCM returns OpenStack external cloud controller manager current image
// with tag specified to k8s version
func (tf *TemplateFunctions) OpenStackCCMTag() string {
var tag string
parsed, err := util.ParseKubernetesVersion(tf.Cluster.Spec.KubernetesVersion)
if err != nil {
tag = "latest"
} else {
if parsed.Minor == 24 {
tag = "v1.24.6"
} else if parsed.Minor == 25 {
tag = "v1.25.5"
} else if parsed.Minor == 26 {
tag = "v1.26.2"
} else if parsed.Minor == 27 {
tag = "v1.27.1"
} else {
// otherwise we use always .0 ccm image, if needed that can be overrided using clusterspec
tag = fmt.Sprintf("v%d.%d.0", parsed.Major, parsed.Minor)
}
}
return tag
}
// OpenStackCSI returns OpenStack csi current image
// with tag specified to k8s version
func (tf *TemplateFunctions) OpenStackCSITag() string {
var tag string
parsed, err := util.ParseKubernetesVersion(tf.Cluster.Spec.KubernetesVersion)
if err != nil {
tag = "latest"
} else {
if parsed.Minor == 24 {
tag = "v1.24.6"
} else if parsed.Minor == 25 {
tag = "v1.25.5"
} else if parsed.Minor == 26 {
tag = "v1.26.2"
} else if parsed.Minor == 27 {
tag = "v1.27.1"
} else {
// otherwise we use always .0 csi image, if needed that can be overrided using cloud config spec
tag = fmt.Sprintf("v%d.%d.0", parsed.Major, parsed.Minor)
}
}
return tag
}
// GetNodeInstanceGroups returns a map containing the defined instance groups of role "Node".
func (tf *TemplateFunctions) GetNodeInstanceGroups() map[string]kops.InstanceGroupSpec {
nodegroups := make(map[string]kops.InstanceGroupSpec)
for _, ig := range tf.KopsModelContext.InstanceGroups {
if ig.Spec.Role == kops.InstanceGroupRoleNode {
nodegroups[ig.ObjectMeta.Name] = ig.Spec
}
}
return nodegroups
}
type ClusterAutoscalerNodeGroup struct {
AutoScale *bool
MinSize int32
MaxSize int32
Other string
}
// GetClusterAutoscalerGroups returns a map containing ClusterAutoscaler info for each instance group of type Node.
func (tf *TemplateFunctions) GetClusterAutoscalerNodeGroups() map[string]ClusterAutoscalerNodeGroup {
cluster := tf.Cluster
groups := make(map[string]ClusterAutoscalerNodeGroup)
for _, ig := range tf.KopsModelContext.InstanceGroups {
if ig.Spec.Role == kops.InstanceGroupRoleNode && (ig.Spec.Autoscale == nil || fi.ValueOf(ig.Spec.Autoscale)) {
group := ClusterAutoscalerNodeGroup{
AutoScale: ig.Spec.Autoscale,
MinSize: fi.ValueOf(ig.Spec.MinSize),
MaxSize: fi.ValueOf(ig.Spec.MaxSize),
}
if cluster.Spec.GetCloudProvider() == kops.CloudProviderGCE {
cloud := tf.cloud.(gce.GCECloud)
format := "https://www.googleapis.com/compute/v1/projects/%s/zones/%s/instanceGroups/%s"
group.Other = fmt.Sprintf(format, cloud.Project(), ig.Spec.Zones[0], gce.NameForInstanceGroupManager(cluster, ig, ig.Spec.Zones[0]))
} else {
group.Other = ig.Name + "." + cluster.Name
}
groups[ig.Name] = group
}
}
return groups
}
func (tf *TemplateFunctions) architectureOfAMI(amiID string) string {
image, _ := tf.cloud.(awsup.AWSCloud).ResolveImage(amiID)
switch *image.Architecture {
case "x86_64":
return "amd64"
}
return "arm64"
}
type podIdentityWebhookMapping struct {
RoleARN string
Audience string
UseRegionalSTS bool
TokenExpiration int64
}
func (tf *TemplateFunctions) podIdentityWebhookConfigMapData() (string, error) {
sas := tf.Cluster.Spec.IAM.ServiceAccountExternalPermissions
mappings := make(map[string]podIdentityWebhookMapping)
for _, sa := range sas {
if sa.AWS == nil {
continue
}
key := sa.Namespace + "/" + sa.Name
mappings[key] = podIdentityWebhookMapping{
RoleARN: fmt.Sprintf("arn:%s:iam::%s:role/%s", tf.AWSPartition, tf.AWSAccountID, iam.IAMNameForServiceAccountRole(sa.Name, sa.Namespace, tf.ClusterName())),