-
Notifications
You must be signed in to change notification settings - Fork 397
/
kubernetes.go
2551 lines (2219 loc) · 90.1 KB
/
kubernetes.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 2018 The Doctl Authors All rights reserved.
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.
*/
package commands
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/blang/semver"
"github.com/digitalocean/doctl"
"github.com/digitalocean/doctl/commands/displayers"
"github.com/digitalocean/doctl/do"
"github.com/digitalocean/godo"
"github.com/google/uuid"
"github.com/spf13/cobra"
"github.com/spf13/viper"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kubeerrors "k8s.io/apimachinery/pkg/util/errors"
clientauthentication "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
const (
maxAPIFailures = 5
timeoutFetchingKubeconfig = 30 * time.Second
defaultKubernetesNodeSize = "s-1vcpu-2gb"
defaultKubernetesNodeCount = 3
defaultKubernetesRegion = "nyc1"
defaultKubernetesLatestVersion = "latest"
execCredentialKind = "ExecCredential"
workflowDesc = `
A typical workflow is to use ` + "`" + `doctl kubernetes cluster create` + "`" + ` to create the cluster on DigitalOcean's infrastructure, then call ` + "`" + `doctl kubernetes cluster kubeconfig` + "`" + ` to configure ` + "`" + `kubectl` + "`" + ` to connect to the cluster. You are then able to use ` + "`" + `kubectl` + "`" + ` to create and manage workloads.`
optionsDesc = `
The commands under ` + "`" + `doctl kubernetes options` + "`" + ` retrieve values used while creating clusters, such as the list of regions where cluster creation is supported.`
)
var getCurrentAuthContextFn = defaultGetCurrentAuthContextFn
func defaultGetCurrentAuthContextFn() string {
if Context != "" {
return Context
}
if authContext := viper.GetString("context"); authContext != "" {
return authContext
}
return doctl.ArgDefaultContext
}
func errNoClusterByName(name string) error {
return fmt.Errorf("no cluster goes by the name %q", name)
}
func errAmbiguousClusterName(name string, ids []string) error {
return fmt.Errorf("many clusters go by the name %q, they have the following IDs: %v", name, ids)
}
func errNoPoolByName(name string) error {
return fmt.Errorf("No node pool goes by the name %q", name)
}
func errAmbiguousPoolName(name string, ids []string) error {
return fmt.Errorf("Many node pools go by the name %q, they have the following IDs: %v", name, ids)
}
func errNoClusterNodeByName(name string) error {
return fmt.Errorf("No node goes by the name %q", name)
}
func errAmbiguousClusterNodeName(name string, ids []string) error {
return fmt.Errorf("Many nodes go by the name %q, they have the following IDs: %v", name, ids)
}
// Kubernetes creates the kubernetes command.
func Kubernetes() *Command {
cmd := &Command{
Command: &cobra.Command{
Use: "kubernetes",
Aliases: []string{"kube", "k8s", "k"},
Short: "Displays commands to manage Kubernetes clusters and configurations",
Long: "The commands under `doctl kubernetes` are for managing Kubernetes clusters and viewing configuration options relating to clusters." + workflowDesc + optionsDesc,
GroupID: manageResourcesGroup,
},
}
cmd.AddCommand(kubernetesCluster())
cmd.AddCommand(kubernetesOptions())
cmd.AddCommand(kubernetesOneClicks())
return cmd
}
// KubeconfigProvider allows a user to read from a remote and local Kubeconfig, and write to a
// local Kubeconfig.
type KubeconfigProvider interface {
Remote(kube do.KubernetesService, clusterID string, expirySeconds int) (*clientcmdapi.Config, error)
Local() (*clientcmdapi.Config, error)
Write(config *clientcmdapi.Config) error
ConfigPath() string
}
type kubeconfigProvider struct {
pathOptions *clientcmd.PathOptions
}
// Remote returns the kubeconfig for the cluster with the given ID from DOKS.
func (p *kubeconfigProvider) Remote(kube do.KubernetesService, clusterID string, expirySeconds int) (*clientcmdapi.Config, error) {
var kubeconfig []byte
var err error
if expirySeconds > 0 {
kubeconfig, err = kube.GetKubeConfigWithExpiry(clusterID, int64(expirySeconds))
} else {
kubeconfig, err = kube.GetKubeConfig(clusterID)
}
if err != nil {
return nil, err
}
return clientcmd.Load(kubeconfig)
}
// Local reads the kubeconfig from the user's local kubeconfig file.
func (p *kubeconfigProvider) Local() (*clientcmdapi.Config, error) {
config, err := p.pathOptions.GetStartingConfig()
if err != nil {
if a, ok := err.(kubeerrors.Aggregate); ok {
_, isSnap := os.LookupEnv("SNAP")
for _, err := range a.Errors() {
// this should NOT be a contains check but they are formatting the
// error without implementing an unwrap (so the original permission
// error type is lost).
if strings.Contains(err.Error(), "permission denied") && isSnap {
warn("Using the doctl Snap? Grant access to the doctl:kube-config plug to use this command with: sudo snap connect doctl:kube-config")
return nil, err
}
}
}
return nil, err
}
return config, nil
}
// Write either writes to or updates an existing local kubeconfig file.
func (p *kubeconfigProvider) Write(config *clientcmdapi.Config) error {
err := clientcmd.ModifyConfig(p.pathOptions, *config, false)
if err != nil {
_, ok := os.LookupEnv("SNAP")
if os.IsPermission(err) && ok {
warn("Using the doctl Snap? Grant access to the doctl:kube-config plug to use this command with: sudo snap connect doctl:kube-config")
}
return err
}
return nil
}
func (p *kubeconfigProvider) ConfigPath() string {
path := p.pathOptions.GetDefaultFilename()
if _, err := os.Stat(filepath.Dir(path)); os.IsNotExist(err) {
if _, ok := os.LookupEnv("SNAP"); ok {
warn("Using the doctl Snap? Please create the directory: %q before trying again", filepath.Dir(path))
}
}
return path
}
// KubernetesCommandService is used to execute Kubernetes commands.
type KubernetesCommandService struct {
KubeconfigProvider KubeconfigProvider
}
func kubernetesCommandService() *KubernetesCommandService {
return &KubernetesCommandService{
KubeconfigProvider: &kubeconfigProvider{
pathOptions: clientcmd.NewDefaultPathOptions(),
},
}
}
func kubernetesCluster() *Command {
cmd := &Command{
Command: &cobra.Command{
Use: "cluster",
Aliases: []string{"clusters", "c"},
Short: "Display commands for managing Kubernetes clusters",
Long: "The commands under `doctl kubernetes cluster` are for the management of Kubernetes clusters." + workflowDesc,
},
}
k8sCmdService := kubernetesCommandService()
cmd.AddCommand(kubernetesKubeconfig())
cmd.AddCommand(kubernetesNodePools())
cmd.AddCommand(kubernetesRegistryIntegration())
nodePoolDetails := `- A list of node pools available inside the cluster`
clusterDetails := `
- A unique ID for the cluster
- A human-readable name for the cluster
- The slug identifying the region where the Kubernetes cluster is located
- The slug identifying the cluster's Kubernetes version. If set to a minor version, the latest patch version for that minor version is returned. For example, if the cluster is set to ` + "`" + `1.14` + "`" + `, the command would return ` + "`" + `1.14.6-do.1` + "`" + `. If it is set to ` + "`" + `latest` + "`" + `, the latest published version is used.
- A boolean value indicating whether the cluster automatically upgrades to new patch releases during its maintenance window.
- An object containing a "state" attribute whose value is set to a string indicating the current status of the node. Potential values: ` + "`" + `running` + "`" + `, ` + "`" + `provisioning` + "`" + `, ` + "`" + `errored` + "`" + `.`
cmdKubernetesClusterGet := CmdBuilder(cmd, k8sCmdService.RunKubernetesClusterGet, "get <id|name>", "Retrieve details about a Kubernetes cluster", `
Retrieves the following details about a Kubernetes cluster: `+clusterDetails+`
- The base URL of the cluster's Kubernetes API server
- The public IPv4 address of the cluster's Kubernetes API server
- The range of IP addresses in the overlay network of the Kubernetes cluster, in CIDR notation
- The range of assignable IP addresses for services running in the Kubernetes cluster, in CIDR notation
- An array of tags applied to the Kubernetes cluster. All clusters are automatically tagged `+"`"+`k8s`+"`"+` and `+"`"+`k8s:$K8S_CLUSTER_ID`+"`"+`.
- When the Kubernetes cluster was created, in ISO8601 combined date and time format
- When the Kubernetes cluster was last updated, in ISO8601 combined date and time format
`+nodePoolDetails,
Writer, aliasOpt("g"), displayerType(&displayers.KubernetesClusters{}))
cmdKubernetesClusterGet.Example = `The following example retrieve details about a Kubernetes cluster named ` + "`" + `example-cluster` + "`" + `: doctl kubernetes cluster get example-cluster`
KubernetesClusterList := CmdBuilder(cmd, k8sCmdService.RunKubernetesClusterList, "list", "Retrieve the list of Kubernetes clusters for your account", `
Retrieves the following details about all Kubernetes clusters that are on your account:`+clusterDetails+nodePoolDetails,
Writer, aliasOpt("ls"), displayerType(&displayers.KubernetesClusters{}))
KubernetesClusterList.Example = `The following example retrieves the list of Kubernetes clusters for your account and uses the ` + "`" + `--format` + "`" + ` flag to return only the name and endpoint for each cluster: doctl kubernetes cluster list --format Name,Endpoint`
cmdKubernetesClusterGetUpgrades := CmdBuilder(cmd, k8sCmdService.RunKubernetesClusterGetUpgrades, "get-upgrades <id|name>",
"Retrieve a list of available Kubernetes version upgrades", `
Retrieves a list of slugs representing Kubernetes upgrade versions you can use to upgrade the cluster. To upgrade your cluster, use the `+"`"+`doctl kubernetes cluster upgrade`+"`"+` command.
`, Writer, aliasOpt("gu"))
cmdKubernetesClusterGetUpgrades.Example = `The following example retrieves a list of available Kubernetes version upgrades for a cluster named ` + "`" + `example-cluster` + "`" + `: doctl kubernetes cluster get-upgrades example-cluster`
cmdKubeClusterCreate := CmdBuilder(cmd, k8sCmdService.RunKubernetesClusterCreate(defaultKubernetesNodeSize,
defaultKubernetesNodeCount), "create <name>", "Create a Kubernetes cluster", `
Creates a Kubernetes cluster given the specified options and using the specified name. Before creating the cluster, you can use `+"`"+`doctl kubernetes options`+"`"+` to see possible values for the various configuration flags.
If no configuration flags are used, a three-node cluster with a single node pool is created in the `+"`"+`nyc1`+"`"+` region, using the latest Kubernetes version.
After creating a cluster, a configuration context is added to kubectl and made active so that you can begin managing your new cluster immediately.`,
Writer, aliasOpt("c"))
AddStringFlag(cmdKubeClusterCreate, doctl.ArgRegionSlug, "", defaultKubernetesRegion,
"A `slug` indicating which region to create the cluster in. Use the `doctl kubernetes options regions` command for a list of options", requiredOpt())
AddStringFlag(cmdKubeClusterCreate, doctl.ArgClusterVersionSlug, "", "latest",
"A `slug` indicating which Kubernetes version to use when creating the cluster. Use the `doctl kubernetes options versions` command for a list of options")
AddStringFlag(cmdKubeClusterCreate, doctl.ArgClusterVPCUUID, "", "",
"The UUID of a VPC network to create the cluster in. Must be the UUID of a valid VPC in the same region specified for the cluster. If a VPC is not specified, the cluster is placed in the default VPC network for the region.")
AddBoolFlag(cmdKubeClusterCreate, doctl.ArgAutoUpgrade, "", false,
"Enables automatic upgrades to new patch releases during the cluster's maintenance window. Defaults to `false`. To enable automatic upgrade, supply `--auto-upgrade=true`.")
AddBoolFlag(cmdKubeClusterCreate, doctl.ArgSurgeUpgrade, "", true,
"Enables surge-upgrade for the cluster")
AddBoolFlag(cmdKubeClusterCreate, doctl.ArgHA, "", false,
"Creates the cluster with a highly-available control plane. Defaults to false. To enable the HA control plane, supply --ha=true.")
AddStringSliceFlag(cmdKubeClusterCreate, doctl.ArgTag, "", nil,
"A comma-separated list of `tags` to apply to the cluster, in addition to the default tags of `k8s` and `k8s:$K8S_CLUSTER_ID`.")
AddStringFlag(cmdKubeClusterCreate, doctl.ArgSizeSlug, "",
defaultKubernetesNodeSize,
"The machine `size` to use when creating nodes in the default node pool (incompatible with --"+doctl.ArgClusterNodePool+"). Use the `doctl kubernetes options sizes` command for a list of possible values.")
AddStringSliceFlag(cmdKubeClusterCreate, doctl.ArgOneClicks, "", nil, "A comma-separated list of 1-click `applications` to install on the Kubernetes cluster. Use the `doctl kubernetes 1-click list` command for a list of available 1-click applications.")
AddIntFlag(cmdKubeClusterCreate, doctl.ArgNodePoolCount, "",
defaultKubernetesNodeCount,
"The number of nodes in the default node pool (incompatible with --"+doctl.ArgClusterNodePool+")")
AddStringSliceFlag(cmdKubeClusterCreate, doctl.ArgClusterNodePool, "", nil,
`A comma-separated list of `+"`node-pools`"+`, defined using semicolon-separated configuration values and surrounded by quotes (incompatible with --`+doctl.ArgSizeSlug+` and --`+doctl.ArgNodePoolCount+`).
Format: `+"`"+`"name=your-name;size=size_slug;count=5;tag=tag1;tag=tag2;label=key1=value1;label=key2=label2;taint=key1=value1:NoSchedule;taint=key2:NoExecute"`+"`"+` where:
- `+"`"+`name`+"`"+`: The name of the node pool, which must be unique in the cluster
- `+"`"+`size`+"`"+`: The machine size of the nodes to use. Use the `+"`"+`doctl kubernetes options sizes`+"`"+` command for a list of available options.
- `+"`"+`count`+"`"+`: The number of nodes to create
- `+"`"+`tag`+"`"+`: A comma-separated list of tags to apply to nodes in the pool
- `+"`"+`label`+"`"+`: A label in `+"`"+`key=value`+"`"+` notation. Repeat to add multiple labels at once.
- `+"`"+`taint`+"`"+`: Taint in `+"`"+`key=value:effect`+"`"+` notation. Repeat to add multiple taints at once.
- `+"`"+`auto-scale`+"`"+`: Enables cluster auto-scaling on the node pool (boolean).
- `+"`"+`min-nodes`+"`"+`: The minimum number of nodes that the cluster can be auto-scaled to. The value will be 0 if auto_scale is set to false. Scale-to-zero is not supported.
- `+"`"+`max-nodes`+"`"+`: The maximum number of nodes that can be auto-scaled to.`)
AddBoolFlag(cmdKubeClusterCreate, doctl.ArgClusterUpdateKubeconfig, "", true,
"Adds a configuration context for the new cluster to your kubectl")
AddBoolFlag(cmdKubeClusterCreate, doctl.ArgCommandWait, "", true,
"Instructs the terminal to wait for the action to complete before returning control to the user")
AddBoolFlag(cmdKubeClusterCreate, doctl.ArgSetCurrentContext, "", true,
"Sets the current kubectl context to that of the new cluster")
AddStringFlag(cmdKubeClusterCreate, doctl.ArgMaintenanceWindow, "", "any=00:00",
"Sets the beginning of the `schedule` for the four hour maintenance window for the cluster. The syntax format is: `day=HH:MM`, where time is in UTC. Day can be: `any`, `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday"+"`.")
cmdKubeClusterCreate.Example = `The following example creates a cluster named ` + "`" + `example-cluster` + "`" + ` in the ` + "`" + `nyc1` + "`" + ` region with a node pool, using Kubernetes version ` + "`" + `1.28.2-do.0` + "`" + `: doctl kubernetes cluster create example-cluster --region nyc1 --version 1.28.2-do.0 --maintenance-window saturday=02:00 --node-pool "name=example-pool;size=s-2vcpu-2gb;count=5;tag=web;tag=frontend;label=key1=value1;label=key2=label2;taint=key1=value1:NoSchedule;taint=key2:NoExecute"`
cmdKubeClusterUpdate := CmdBuilder(cmd, k8sCmdService.RunKubernetesClusterUpdate, "update <id|name>",
"Update a Kubernetes cluster's configuration", `
Updates the configuration values for a Kubernetes cluster. The cluster must be referred to by its name or ID. Use the `+"`"+`doctl kubernetes cluster list`+"`"+` command to get a list of clusters on your account.`, Writer, aliasOpt("u"))
AddStringFlag(cmdKubeClusterUpdate, doctl.ArgClusterName, "", "",
"Specifies a new cluster name")
AddStringSliceFlag(cmdKubeClusterUpdate, doctl.ArgTag, "", nil,
"A comma-separated list of tags to apply to the cluster. This removes other user-provided tags from the cluster if they are not specified in this argument.")
AddBoolFlag(cmdKubeClusterUpdate, doctl.ArgAutoUpgrade, "", false,
"Indicates whether the cluster automatically upgrades to new patch releases during its maintenance window. To enable automatic upgrade, use `--auto-upgrade=true`.")
AddBoolFlag(cmdKubeClusterUpdate, doctl.ArgSurgeUpgrade, "", false,
"Enables surge-upgrade for the cluster")
AddBoolFlag(cmdKubeClusterUpdate, doctl.ArgHA, "", false,
"Enables the highly-available control plane for the cluster")
AddBoolFlag(cmdKubeClusterUpdate, doctl.ArgClusterUpdateKubeconfig, "",
true, "Updates the cluster in your kubeconfig")
AddBoolFlag(cmdKubeClusterUpdate, doctl.ArgSetCurrentContext, "", true,
"Sets the current kubectl context to that of the new cluster")
AddStringFlag(cmdKubeClusterUpdate, doctl.ArgMaintenanceWindow, "", "any=00:00",
"Sets the beginning of the four hour maintenance window for the cluster. Syntax is in the format: 'day=HH:MM', where time is in UTC. Day can be: `any`, `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, `sunday"+"`.")
cmdKubeClusterUpdate.Example = `The following example updates a cluster named ` + "`" + `example-cluster` + "`" + ` to enable automatic upgrades and sets the maintenance window to ` + "`" + `saturday=02:00` + "`" + `: doctl kubernetes cluster update example-cluster --auto-upgrade --maintenance-window saturday=02:00`
cmdKubeClusterUpgrade := CmdBuilder(cmd, k8sCmdService.RunKubernetesClusterUpgrade,
"upgrade <id|name>", "Upgrades a cluster to a new Kubernetes version", `
Upgrades a Kubernetes cluster. By default, this upgrades the cluster to the latest available release, but you can also specify any version listed for your cluster by using `+"`"+`doctl k8s get-upgrades`+"`"+`.`, Writer)
AddStringFlag(cmdKubeClusterUpgrade, doctl.ArgClusterVersionSlug, "", "latest",
`The Kubernetes version to upgrade to. Use the `+"`"+`doctl k8s get-upgrades <cluster>`+"`"+` command for a list of available versions.
The special value `+"`"+`latest`+"`"+` selects the most recent patch version for your cluster's minor version.
For example, if a cluster is on 1.12.1 and upgrades are available to 1.12.3 and 1.13.1, the `+"`"+`latest`+"`"+` flag upgrades the cluster to 1.12.3.`)
cmdKubeClusterUpgrade.Example = `The following example upgrades a cluster named ` + "`" + `example-cluster` + "`" + ` to version 1.28.2: doctl kubernetes cluster upgrade example-cluster --version 1.28.2-do.0`
cmdKubeClusterDelete := CmdBuilder(cmd, k8sCmdService.RunKubernetesClusterDelete,
"delete <id|name>...", "Delete Kubernetes clusters ", `
Deletes the specified Kubernetes clusters and the Droplets associated with them. To delete all other DigitalOcean resources created during the operation of the clusters, such as load balancers, volumes or volume snapshots, use the `+"`"+`--dangerous`+"`"+` flag.
`, Writer, aliasOpt("d", "rm"))
AddBoolFlag(cmdKubeClusterDelete, doctl.ArgForce, doctl.ArgShortForce, false,
"Deletes the cluster without a confirmation prompt")
AddBoolFlag(cmdKubeClusterDelete, doctl.ArgClusterUpdateKubeconfig, "", true,
"Remove the deleted cluster from your kubeconfig")
AddBoolFlag(cmdKubeClusterDelete, doctl.ArgDangerous, "", false,
"Deletes the cluster's associated resources like load balancers, volumes and volume snapshots")
cmdKubeClusterDelete.Example = `The following example deletes a cluster named ` + "`" + `example-cluster` + "`" + `: doctl kubernetes cluster delete example-cluster`
cmdKubeClusterDeleteSelective := CmdBuilder(cmd, k8sCmdService.RunKubernetesClusterDeleteSelective,
"delete-selective <id|name>", "Delete a Kubernetes cluster and selectively delete resources associated with it", `
Deletes the specified Kubernetes cluster and Droplets associated with it. It also deletes the specified associated resources. Associated resources can be load balancers, volumes and volume snapshots.
`, Writer, aliasOpt("ds"))
AddBoolFlag(cmdKubeClusterDeleteSelective, doctl.ArgForce, doctl.ArgShortForce, false,
"Deletes the cluster without a confirmation prompt")
AddBoolFlag(cmdKubeClusterDeleteSelective, doctl.ArgClusterUpdateKubeconfig, "", true,
"Removes the deleted cluster from your kubeconfig")
AddStringSliceFlag(cmdKubeClusterDeleteSelective, doctl.ArgVolumeList, "", nil,
"A comma-separated list of volume IDs or names to delete")
AddStringSliceFlag(cmdKubeClusterDeleteSelective, doctl.ArgVolumeSnapshotList, "", nil,
"A comma-separated list of volume snapshot IDs or names to delete")
AddStringSliceFlag(cmdKubeClusterDeleteSelective, doctl.ArgLoadBalancerList, "", nil,
"A comma-separated list of load balancer IDs or names to delete")
cmdKubeClusterDeleteSelective.Example = `The following example deletes a cluster named ` + "`" + `example-cluster` + "`" + ` and selectively deletes the specified load balancers and volumes associated with the cluster: doctl kubernetes cluster delete-selective example-cluster --volume-list "386734086,example-volume" --load-balancer-list "191669331,example-load-balancer"`
cmdKubeClusterListAssociatedResources := CmdBuilder(cmd, k8sCmdService.RunKubernetesClusterListAssociatedResources, "list-associated-resources <id|name>", "Retrieve DigitalOcean resources associated with a Kubernetes cluster", `
Retrieves the following details for a Kubernetes cluster:
- Volume IDs for volumes created by the DigitalOcean CSI driver
- Volume snapshot IDs for volume snapshots created by the DigitalOcean CSI driver
- Load balancer IDs for load balancers managed by the Kubernetes cluster`,
Writer, aliasOpt("ar"), displayerType(&displayers.KubernetesAssociatedResources{}))
cmdKubeClusterListAssociatedResources.Example = `The following example retrieves the associated resources for a cluster named ` + "`" + `example-cluster` + "`" + ` and uses the ` + "`" + `--format` + "`" + ` flag to return only the associated volumes: doctl kubernetes cluster list-associated-resources example-cluster --format Volumes`
return cmd
}
func kubernetesKubeconfig() *Command {
cmd := &Command{
Command: &cobra.Command{
Use: "kubeconfig",
Aliases: []string{"kubecfg", "k8scfg", "config", "cfg"},
Short: "Display commands for managing your local kubeconfig",
Long: "The commands under `doctl kubernetes cluster kubeconfig` are used to manage Kubernetes cluster credentials on your local machine. The credentials are used as authentication contexts with `kubectl`, the Kubernetes command-line interface.",
},
}
k8sCmdService := kubernetesCommandService()
cmdShowConfig := CmdBuilder(cmd, k8sCmdService.RunKubernetesKubeconfigShow, "show <cluster-id|cluster-name>", "Show a Kubernetes cluster's kubeconfig YAML", `
Returns the raw YAML for the specified cluster's kubeconfig.`, Writer, aliasOpt("p", "g"))
AddIntFlag(cmdShowConfig, doctl.ArgKubeConfigExpirySeconds, "", 0,
"The length of time the cluster credentials are valid for, in seconds. By default, the credentials expire after seven days.")
cmdShowConfig.Example = `The following example shows the kubeconfig YAML for a cluster named ` + "`" + `example-cluster` + "`" + `: doctl kubernetes cluster kubeconfig show example-cluster`
execCredDesc := "INTERNAL: This hidden command is for printing a cluster's exec credential"
cmdExecCredential := CmdBuilder(cmd, k8sCmdService.RunKubernetesKubeconfigExecCredential, "exec-credential <cluster-id>", execCredDesc, execCredDesc, Writer, hiddenCmd())
AddStringFlag(cmdExecCredential, doctl.ArgVersion, "", "", "")
cmdSaveConfig := CmdBuilder(cmd, k8sCmdService.RunKubernetesKubeconfigSave, "save <cluster-id|cluster-name>", "Save a cluster's credentials to your local kubeconfig", `
Adds the credentials for the specified cluster to your local kubeconfig. After this, your kubectl installation can directly manage the specified cluster.
`, Writer, aliasOpt("s"))
AddBoolFlag(cmdSaveConfig, doctl.ArgSetCurrentContext, "", true, "Sets the current kubectl context to that of the newest cluster in your account")
AddIntFlag(cmdSaveConfig, doctl.ArgKubeConfigExpirySeconds, "", 0,
"The length of time the cluster credentials are valid for, in seconds. By default, the credentials are automatically renewed as needed.")
AddStringFlag(cmdSaveConfig, doctl.ArgKubernetesAlias, "", "", "An alias for the cluster context name. Defaults to 'do-[region]-[cluster-name]'")
cmdSaveConfig.Example = `The following example saves the credentials for a cluster named ` + "`" + `example-cluster` + "`" + ` to your local kubeconfig: doctl kubernetes cluster kubeconfig save example-cluster`
cmdKubeKubeconfigRemove := CmdBuilder(cmd, k8sCmdService.RunKubernetesKubeconfigRemove, "remove <cluster-id|cluster-name>", "Remove a cluster's credentials from your local kubeconfig", `
This command removes the specified cluster's credentials from your local kubeconfig. After running this command, you cannot use `+"`"+`kubectl`+"`"+` to interact with your cluster.
`, Writer, aliasOpt("d", "rm"))
cmdKubeKubeconfigRemove.Example = `The following example removes the credentials for a cluster named ` + "`" + `example-cluster` + "`" + ` from your local kubeconfig: doctl kubernetes cluster kubeconfig remove example-cluster`
return cmd
}
func kubeconfigCachePath() string {
return filepath.Join(defaultConfigHome(), "cache", "exec-credential")
}
func kubernetesNodePools() *Command {
cmd := &Command{
Command: &cobra.Command{
Use: "node-pool",
Aliases: []string{"node-pools", "nodepool", "nodepools", "pool", "pools", "np", "p"},
Short: "Display commands for managing node pools",
Long: "The commands under `node-pool` are for managing Kubernetes cluster's node pools. You can use these commands to create or delete node pools, enable autoscaling, and more.",
},
}
k8sCmdService := kubernetesCommandService()
cmdKubeNodePoolGet := CmdBuilder(cmd, k8sCmdService.RunKubernetesNodePoolGet, "get <cluster-id|cluster-name> <pool-id|pool-name>",
"Retrieve information about a cluster's node pool", `
Retrieves information about the specified node pool in the specified cluster, including:
- The node pool ID
- The slug indicating the machine size of the nodes, such as `+"`"+`s-1vcpu-2gb`+"`"+`
- The number of nodes in the pool
- The tags applied to the node pool
- The names of the nodes
Specifying `+"`"+`--output=json`+"`"+` when calling this command returns additional information about the individual nodes in the response, such as their IDs, status, creation time, and update time.
`, Writer, aliasOpt("g"),
displayerType(&displayers.KubernetesNodePools{}))
cmdKubeNodePoolGet.Example = `The following example retrieves information about a node pool named ` + "`" + `example-pool` + "`" + ` in a cluster named ` + "`" + `example-cluster` + "`" + `: doctl kubernetes cluster node-pool get example-cluster example-pool`
cmdKubeNodePoolList := CmdBuilder(cmd, k8sCmdService.RunKubernetesNodePoolList, "list <cluster-id|cluster-name>",
"List a cluster's node pools", `
Retrieves information about the specified cluster's node pools, including:
- The node pool ID
- The slug indicating the machine size of the nodes, such as `+"`"+`s-1vcpu-2gb`+"`"+`
- The number of nodes in the pool
- The tags applied to the node pool
- The names of the nodes
Specifying `+"`"+`--output=json`+"`"+` when calling this command returns additional information about the individual nodes in the response, such as their IDs, status, creation time, and update time.
`, Writer, aliasOpt("ls"),
displayerType(&displayers.KubernetesNodePools{}))
cmdKubeNodePoolList.Example = `The following example retrieves information about all node pools in a cluster named ` + "`" + `example-cluster` + "`" + ` and uses the ` + "`" + `--format` + "`" + ` flag to only return the ID, name, and nodes for each pool: doctl kubernetes cluster node-pool list example-cluster --format ID,Name,Nodes`
cmdKubeNodePoolCreate := CmdBuilder(cmd, k8sCmdService.RunKubernetesNodePoolCreate,
"create <cluster-id|cluster-name>", "Create a new node pool for a cluster", `
Creates a new node pool for the specified cluster. The command requires values for the `+"`"+`--name`+"`"+`, `+"`"+`--size`+"`"+`, and `+"`"+`--count`+"`"+` flags to create a node pool. You can also specify that you'd like to enable autoscaling and set minimum and maximum node poll sizes.
`,
Writer, aliasOpt("c"))
AddStringFlag(cmdKubeNodePoolCreate, doctl.ArgNodePoolName, "", "",
"The name of the node pool", requiredOpt())
AddStringFlag(cmdKubeNodePoolCreate, doctl.ArgSizeSlug, "", "",
"The `size` of the nodes in the node pool. Use the `doctl kubernetes options sizes` command for a list of possible values.", requiredOpt())
AddIntFlag(cmdKubeNodePoolCreate, doctl.ArgNodePoolCount, "", 0,
"The number of nodes in the node pool", requiredOpt())
AddStringSliceFlag(cmdKubeNodePoolCreate, doctl.ArgTag, "", nil,
"A tag to apply to the node pool. Repeat this flag to specify additional tags. An existing tag is removed from the node pool if it is not specified by any flag.")
AddStringSliceFlag(cmdKubeNodePoolCreate, doctl.ArgKubernetesLabel, "", nil,
"A label in key=value notation to apply to the node pool. Repeat this flag to specify additional labels. An existing label is removed from the node pool if it is not specified by any flag.")
AddStringSliceFlag(cmdKubeNodePoolCreate, doctl.ArgKubernetesTaint, "", nil,
"Taint in `key=value:effect` notation to apply to the node pool. Repeat this flag to specify additional taints. Set to an empty string (\"\") to clear all taints. An existing taint is removed from the node pool if it is not specified by any flag.")
AddBoolFlag(cmdKubeNodePoolCreate, doctl.ArgNodePoolAutoScale, "", false,
"Enables auto-scaling on the node pool")
AddIntFlag(cmdKubeNodePoolCreate, doctl.ArgNodePoolMinNodes, "", 0,
"The minimum number of nodes in the node pool when autoscaling is enabled")
AddIntFlag(cmdKubeNodePoolCreate, doctl.ArgNodePoolMaxNodes, "", 0,
"The maximum number of nodes in the node pool when autoscaling is enabled")
cmdKubeNodePoolCreate.Example = `The following example creates a node pool named ` + "`" + `example-pool` + "`" + ` in a cluster named ` + "`" + `example-cluster` + "`" + `: doctl kubernetes cluster node-pool create example-cluster --name example-pool --size s-1vcpu-2gb --count 3 --taint "key1=value1:NoSchedule" --taint "key2:NoExecute"`
cmdKubeNodePoolUpdate := CmdBuilder(cmd, k8sCmdService.RunKubernetesNodePoolUpdate,
"update <cluster-id|cluster-name> <pool-id|pool-name>",
"Update an existing node pool in a cluster", "Updates a node pool in a cluster. You can update any value for which there is a flag.", Writer, aliasOpt("u"))
AddStringFlag(cmdKubeNodePoolUpdate, doctl.ArgNodePoolName, "", "", "The name of the node pool")
AddIntFlag(cmdKubeNodePoolUpdate, doctl.ArgNodePoolCount, "", 0,
"The number of nodes in the node pool")
AddStringSliceFlag(cmdKubeNodePoolUpdate, doctl.ArgTag, "", nil,
"A tag to apply to the node pool. Repeat this flag to specify additional tags. An existing tag is removed from the node pool if it is not specified by any flag.")
AddStringSliceFlag(cmdKubeNodePoolUpdate, doctl.ArgKubernetesLabel, "", nil,
"A label in `key=value` notation to apply to the node pool. Repeat this flag to specify additional labels. Existing labels are removed from the node pool if they are not specified in the updated value.")
AddStringSliceFlag(cmdKubeNodePoolUpdate, doctl.ArgKubernetesTaint, "", nil,
"Taint in `key=value:effect` notation to apply to the node pool. Repeat this flag to specify additional taints. Set to an empty string (\"\") to clear all taints. An existing taint is removed from the node pool if it is not specified by any flag.")
AddBoolFlag(cmdKubeNodePoolUpdate, doctl.ArgNodePoolAutoScale, "", false,
"Enables auto-scaling on the node pool")
AddIntFlag(cmdKubeNodePoolUpdate, doctl.ArgNodePoolMinNodes, "", 0,
"The minimum number of nodes in the node pool when autoscaling is enabled")
AddIntFlag(cmdKubeNodePoolUpdate, doctl.ArgNodePoolMaxNodes, "", 0,
"The maximum number of nodes in the node pool when autoscaling is enabled")
cmdKubeNodePoolUpdate.Example = `The following example updates a node pool named ` + "`" + `example-pool` + "`" + ` in a cluster named ` + "`" + `example-cluster` + "`" + `: doctl kubernetes cluster node-pool update example-cluster example-pool --count 5 --taint "key1=value1:NoSchedule" --taint "key2:NoExecute"`
recycleDesc := "DEPRECATED: Use `replace-node`. Recycle nodes in a node pool"
cmdKubeNodePoolRecycle := CmdBuilder(cmd, k8sCmdService.RunKubernetesNodePoolRecycle,
"recycle <cluster-id|cluster-name> <pool-id|pool-name>", recycleDesc, recycleDesc, Writer, aliasOpt("r"), hiddenCmd())
AddStringFlag(cmdKubeNodePoolRecycle, doctl.ArgNodePoolNodeIDs, "", "",
"ID or name of the nodes in the node pool to recycle")
cmdKubeNodePoolDelete := CmdBuilder(cmd, k8sCmdService.RunKubernetesNodePoolDelete,
"delete <cluster-id|cluster-name> <pool-id|pool-name>",
"Delete a node pool", `Deletes a node pool in a cluster, which also removes all the nodes inside that pool. You cannot reverse this action.`, Writer, aliasOpt("d", "rm"))
AddBoolFlag(cmdKubeNodePoolDelete, doctl.ArgForce, doctl.ArgShortForce,
false, "Deletes node pool without a confirmation prompt")
cmdKubeNodePoolDelete.Example = `The following example deletes a node pool named ` + "`" + `example-pool` + "`" + ` in a cluster named ` + "`" + `example-cluster` + "`" + `: doctl kubernetes cluster node-pool delete example-cluster example-pool`
cmdKubeNodeDelete := CmdBuilder(cmd, k8sCmdService.RunKubernetesNodeDelete, "delete-node <cluster-id|cluster-name> <pool-id|pool-name> <node-id>", "Delete a node", `
Deletes a node in the specified node pool. By default, this deletion happens gracefully and Kubernetes drains the node of any pods before deleting it.
`, Writer)
AddBoolFlag(cmdKubeNodeDelete, doctl.ArgForce, doctl.ArgShortForce, false, "Deletes the node without a confirmation prompt")
AddBoolFlag(cmdKubeNodeDelete, "skip-drain", "", false, "Skips draining the node before deletion")
cmdKubeNodeDelete.Example = `The following example deletes a node named ` + "`" + `example-node` + "`" + ` in a node pool named ` + "`" + `example-pool` + "`" + `: doctl kubernetes cluster node-pool delete-node example-cluster example-pool example-node`
cmdKubeNodeReplace := CmdBuilder(cmd, k8sCmdService.RunKubernetesNodeReplace, "replace-node <cluster-id|cluster-name> <pool-id|pool-name> <node-id>", "Replace node with a new one", `
Deletes the specified node in the specified node pool, and then creates a new node in its place. This is useful if you suspect a node has entered an undesired state. By default, the deletion happens gracefully and Kubernetes drains the node of any pods before deleting it.
`, Writer)
AddBoolFlag(cmdKubeNodeReplace, doctl.ArgForce, doctl.ArgShortForce, false, "Replaces node without confirmation prompt")
AddBoolFlag(cmdKubeNodeReplace, "skip-drain", "", false, "Skips draining the node before replacement")
cmdKubeNodeReplace.Example = `The following example replaces a node named ` + "`" + `example-node` + "`" + ` in a node pool named ` + "`" + `example-pool` + "`" + `: doctl kubernetes cluster node-pool replace-node example-cluster example-pool example-node`
return cmd
}
func kubernetesRegistryIntegration() *Command {
cmd := &Command{
Command: &cobra.Command{
Use: "registry",
Aliases: []string{"reg"},
Short: "Display commands for integrating clusters with docr",
Long: "The commands under `registry` are for managing DOCR integration with Kubernetes clusters. You can use these commands to add or remove registry from one or more clusters.",
},
}
k8sCmdService := kubernetesCommandService()
cmdKubeRegistryAdd := CmdBuilder(cmd, k8sCmdService.RunKubernetesRegistryAdd,
"add <cluster-id|cluster-name> <cluster-id|cluster-name>", "Add container registry support to Kubernetes clusters", `
Adds container registry support to the specified Kubernetes cluster(s).`,
Writer, aliasOpt("a"))
cmdKubeRegistryAdd.Example = `The following example adds container registry support to a cluster named ` + "`" + `example-cluster` + "`" + `: doctl kubernetes cluster registry add example-cluster`
cmdKubeRegistryRemove := CmdBuilder(cmd, k8sCmdService.RunKubernetesRegistryRemove,
"remove <cluster-id|cluster-name> <cluster-id|cluster-name>", "Remove container registry support from Kubernetes clusters", `
Removes container registry support from the specified Kubernetes cluster(s).`,
Writer, aliasOpt("rm"))
cmdKubeRegistryRemove.Example = `The following example removes container registry support from a cluster named ` + "`" + `example-cluster` + "`" + `: doctl kubernetes cluster registry remove example-cluster`
return cmd
}
// kubernetesOneClicks creates the 1-click command.
func kubernetesOneClicks() *Command {
cmd := &Command{
Command: &cobra.Command{
Use: "1-click",
Short: "Display commands that pertain to kubernetes 1-click applications",
Long: "The commands under `doctl kubernetes 1-click` are for managing DigitalOcean Kubernetes 1-Click applications.",
},
}
cmdKubernetesOneClickList := CmdBuilder(cmd, RunKubernetesOneClickList, "list", "Retrieve a list of Kubernetes 1-Click applications", "Retrieves a list of Kubernetes 1-Click applications you can install on a Kubernetes cluster.", Writer,
aliasOpt("ls"), displayerType(&displayers.OneClick{}))
cmdKubernetesOneClickList.Example = `The following example lists all available 1-click apps for Kubernetes: doctl kubernetes 1-click list`
cmdKubeOneClickInstall := CmdBuilder(cmd, RunKubernetesOneClickInstall, "install <cluster-id>", "Install 1-click apps on a Kubernetes cluster", "Installs 1-click applications on a Kubernetes cluster. Use the `--1-click` flag to specify one or multiple pieces of software to install on the cluster.", Writer, aliasOpt("in"), displayerType(&displayers.OneClick{}))
AddStringSliceFlag(cmdKubeOneClickInstall, doctl.ArgOneClicks, "", nil, "The 1-clicks application to install on the cluster. Multiple 1-clicks can be added simultaneously, for example: `--1-clicks moon,loki,netdata`")
cmdKubeOneClickInstall.Example = `The following example installs Loki and Netdata on a Kubernetes cluster with the ID ` + "`" + `f81d4fae-7dec-11d0-a765-00a0c91e6bf6` + "`" + `: doctl kubernetes 1-click install f81d4fae-7dec-11d0-a765-00a0c91e6bf6> --1-clicks loki,netdata`
return cmd
}
// RunKubernetesOneClickList retrieves a list of 1-clicks for kubernetes.
func RunKubernetesOneClickList(c *CmdConfig) error {
oneClicks := c.OneClicks()
oneClickList, err := oneClicks.List("kubernetes")
if err != nil {
return err
}
items := &displayers.OneClick{OneClicks: oneClickList}
return c.Display(items)
}
// RunKubernetesOneClickInstall installs 1-click apps on a kubernetes cluster.
func RunKubernetesOneClickInstall(c *CmdConfig) error {
oneClicks := c.OneClicks()
if len(c.Args) < 1 {
return doctl.NewMissingArgsErr(c.NS)
}
oneClickSlice, err := c.Doit.GetStringSlice(c.NS, doctl.ArgOneClicks)
if err != nil {
return err
}
oneClickInstall, err := oneClicks.InstallKubernetes(c.Args[0], oneClickSlice)
if err != nil {
return err
}
notice(oneClickInstall)
return nil
}
func kubernetesOptions() *Command {
cmd := &Command{
Command: &cobra.Command{
Use: "options",
Aliases: []string{"opts", "o"},
Short: "List possible option values for use inside Kubernetes commands",
Long: "The `options` commands are used to enumerate values for use with `doctl`'s Kubernetes commands. This is useful in certain cases where flags only accept input that is from a list of possible values, such as Kubernetes versions, datacenter regions, and machine sizes.",
},
}
k8sCmdService := kubernetesCommandService()
k8sVersionDesc := "Lists Kubernetes versions that you can use with DigitalOcean clusters"
CmdBuilder(cmd, k8sCmdService.RunKubeOptionsListVersion, "versions",
k8sVersionDesc, k8sVersionDesc, Writer, aliasOpt("v"))
k8sRegionsDesc := "Lists regions that support DigitalOcean Kubernetes clusters"
CmdBuilder(cmd, k8sCmdService.RunKubeOptionsListRegion, "regions",
k8sRegionsDesc, k8sRegionsDesc, Writer, aliasOpt("r"))
k8sSizesDesc := "Lists machine sizes that you can use in a DigitalOcean Kubernetes cluster"
CmdBuilder(cmd, k8sCmdService.RunKubeOptionsListNodeSizes, "sizes",
k8sSizesDesc, k8sSizesDesc, Writer, aliasOpt("s"))
return cmd
}
// Clusters
// RunKubernetesClusterGet retrieves an existing kubernetes cluster by its identifier.
func (s *KubernetesCommandService) RunKubernetesClusterGet(c *CmdConfig) error {
err := ensureOneArg(c)
if err != nil {
return err
}
clusterIDorName := c.Args[0]
cluster, err := clusterByIDorName(c.Kubernetes(), clusterIDorName)
if err != nil {
return err
}
return displayClusters(c, false, *cluster)
}
// RunKubernetesClusterList lists kubernetes.
func (s *KubernetesCommandService) RunKubernetesClusterList(c *CmdConfig) error {
kube := c.Kubernetes()
list, err := kube.List()
if err != nil {
return err
}
// Check the format flag to determine if the displayer should use the short
// layout of the cluster display. List uses the short version, but to format
// output that includes columns not in the short layout we need the full version.
var short = true
format, err := c.Doit.GetStringSlice(c.NS, doctl.ArgFormat)
if err != nil {
return err
}
if len(format) > 0 {
short = false
}
return displayClusters(c, short, list...)
}
// RunKubernetesClusterGetUpgrades retrieves available upgrade versions for a cluster.
func (s *KubernetesCommandService) RunKubernetesClusterGetUpgrades(c *CmdConfig) error {
err := ensureOneArg(c)
if err != nil {
return err
}
clusterIDorName := c.Args[0]
clusterID, err := clusterIDize(c, clusterIDorName)
if err != nil {
return err
}
kube := c.Kubernetes()
upgrades, err := kube.GetUpgrades(clusterID)
if err != nil {
return err
}
item := &displayers.KubernetesVersions{KubernetesVersions: upgrades}
return c.Display(item)
}
// RunKubernetesClusterCreate creates a new kubernetes with a given configuration.
func (s *KubernetesCommandService) RunKubernetesClusterCreate(defaultNodeSize string, defaultNodeCount int) func(*CmdConfig) error {
return func(c *CmdConfig) error {
err := ensureOneArg(c)
if err != nil {
return err
}
clusterName := c.Args[0]
r := &godo.KubernetesClusterCreateRequest{Name: clusterName}
if err := buildClusterCreateRequestFromArgs(c, r, defaultNodeSize, defaultNodeCount); err != nil {
return err
}
wait, err := c.Doit.GetBool(c.NS, doctl.ArgCommandWait)
if err != nil {
return err
}
update, err := c.Doit.GetBool(c.NS, doctl.ArgClusterUpdateKubeconfig)
if err != nil {
return err
}
setCurrentContext, err := c.Doit.GetBool(c.NS, doctl.ArgSetCurrentContext)
if err != nil {
return err
}
kube := c.Kubernetes()
cluster, err := kube.Create(r)
if err != nil {
return err
}
if wait {
notice("Cluster is provisioning, waiting for cluster to be running")
cluster, err = waitForClusterRunning(kube, cluster.ID)
if err != nil {
warn("Cluster couldn't enter `running` state: %v", err)
}
}
if update {
notice("Cluster created, fetching credentials")
s.tryUpdateKubeconfig(kube, cluster.ID, clusterName, setCurrentContext)
}
oneClickApps, err := c.Doit.GetStringSlice(c.NS, doctl.ArgOneClicks)
if err != nil {
return err
}
if len(oneClickApps) > 0 {
oneClicks := c.OneClicks()
messageResponse, err := oneClicks.InstallKubernetes(cluster.ID, oneClickApps)
if err != nil {
warn("Failed to kick off 1-Click Application(s) install")
} else {
notice(messageResponse)
}
}
return displayClusters(c, true, *cluster)
}
}
// RunKubernetesClusterUpdate updates an existing kubernetes with new configuration.
func (s *KubernetesCommandService) RunKubernetesClusterUpdate(c *CmdConfig) error {
if len(c.Args) == 0 {
return doctl.NewMissingArgsErr(c.NS)
}
update, err := c.Doit.GetBool(c.NS, doctl.ArgClusterUpdateKubeconfig)
if err != nil {
return err
}
setCurrentContext, err := c.Doit.GetBool(c.NS, doctl.ArgSetCurrentContext)
if err != nil {
return err
}
clusterIDorName := c.Args[0]
clusterID, err := clusterIDize(c, clusterIDorName)
if err != nil {
return err
}
r := new(godo.KubernetesClusterUpdateRequest)
if err := buildClusterUpdateRequestFromArgs(c, r); err != nil {
return err
}
kube := c.Kubernetes()
cluster, err := kube.Update(clusterID, r)
if err != nil {
return err
}
if update {
notice("Cluster updated, fetching new credentials")
s.tryUpdateKubeconfig(kube, clusterID, clusterIDorName, setCurrentContext)
}
return displayClusters(c, true, *cluster)
}
func (s *KubernetesCommandService) tryUpdateKubeconfig(kube do.KubernetesService, clusterID, clusterName string, setCurrentContext bool) {
var (
remoteConfig *clientcmdapi.Config
err error
)
ctx, cancel := context.WithTimeout(context.TODO(), timeoutFetchingKubeconfig)
defer cancel()
for {
remoteConfig, err = s.KubeconfigProvider.Remote(kube, clusterID, 0)
if err != nil {
select {
case <-ctx.Done():
warn("Couldn't get credentials for cluster. It will not be added to your kubeconfig: %v", err)
return
case <-time.After(time.Second):
}
} else {
break
}
}
if err := s.writeOrAddToKubeconfig(clusterID, remoteConfig, setCurrentContext, 0); err != nil {
warn("Couldn't write cluster credentials: %v", err)
}
}
// RunKubernetesClusterUpgrade upgrades an existing cluster to a new version.
func (s *KubernetesCommandService) RunKubernetesClusterUpgrade(c *CmdConfig) error {
if len(c.Args) == 0 {
return doctl.NewMissingArgsErr(c.NS)
}
clusterID, err := clusterIDize(c, c.Args[0])
if err != nil {
return err
}
version, available, err := getUpgradeVersionOrLatest(c, clusterID)
if err != nil {
return err
}
if !available {
notice("Cluster is already up-to-date; no upgrades available.")
return nil
}
kube := c.Kubernetes()
err = kube.Upgrade(clusterID, version)
if err != nil {
return err
}
notice("Upgrading cluster to version %v", version)
return nil
}
func getUpgradeVersionOrLatest(c *CmdConfig, clusterID string) (string, bool, error) {
version, err := c.Doit.GetString(c.NS, doctl.ArgClusterVersionSlug)
if err != nil {
return "", false, err
}
if version != "" && version != defaultKubernetesLatestVersion {
return version, true, nil
}
cluster, err := c.Kubernetes().Get(clusterID)
if err != nil {
return "", false, fmt.Errorf("Unable to look up cluster to find the latest version from the API: %v", err)
}
versions, err := c.Kubernetes().GetUpgrades(clusterID)
if err != nil {
return "", false, fmt.Errorf("Unable to look up the latest version from the API: %v", err)
}
if len(versions) == 0 {
return "", false, nil
}
return latestVersionForUpgrade(cluster.VersionSlug, versions)
}
// latestVersionForUpgrade returns the newest patch version from `versions` for
// the minor version of `clusterVersionSlug`. This ensures we never use a
// different minor version than a cluster is running as "latest" for an upgrade,
// since we want minor version upgrades to be an explicit operation.
func latestVersionForUpgrade(clusterVersionSlug string, versions []do.KubernetesVersion) (string, bool, error) {
clusterSV, err := semver.Parse(clusterVersionSlug)
if err != nil {
return "", false, err
}
clusterBucket := fmt.Sprintf("%d.%d", clusterSV.Major, clusterSV.Minor)
// Sort releases into minor-version buckets.
var serr error
releases := versionMapBy(versions, func(v do.KubernetesVersion) string {
sv, err := semver.Parse(v.Slug)
if err != nil {
serr = err
return ""
}
return fmt.Sprintf("%d.%d", sv.Major, sv.Minor)
})
if serr != nil {
return "", false, serr
}
// Find the cluster's minor version in the bucketized available versions.
bucket, ok := releases[clusterBucket]
if !ok {
// No upgrades available within the cluster's minor version.
return "", false, nil
}
// Find the latest version within the bucket.
i, err := versionMaxBy(bucket, func(v do.KubernetesVersion) string {
return v.Slug
})
if err != nil {
return "", false, err
}
return bucket[i].Slug, true, nil
}
// RunKubernetesClusterDelete deletes a Kubernetes cluster
func (s *KubernetesCommandService) RunKubernetesClusterDelete(c *CmdConfig) error {
if len(c.Args) < 1 {
return doctl.NewMissingArgsErr(c.NS)
}
update, err := c.Doit.GetBool(c.NS, doctl.ArgClusterUpdateKubeconfig)
if err != nil {
return err
}
force, err := c.Doit.GetBool(c.NS, doctl.ArgForce)
if err != nil {
return err
}
dangerous, err := c.Doit.GetBool(c.NS, doctl.ArgDangerous)
if err != nil {
return err
}
kube := c.Kubernetes()
for _, cluster := range c.Args {
clusterID, err := clusterIDize(c, cluster)
if err != nil {
return err
}
if force || AskForConfirmDelete("Kubernetes cluster", 1) == nil {
// continue
} else {
return fmt.Errorf("Operation aborted")
}
var kubeconfig []byte
if update {
// get the cluster's kubeconfig before issuing the delete, so that we can
// cleanup the entry from the local file
kubeconfig, err = kube.GetKubeConfig(clusterID)
if err != nil {
warn("Couldn't get credentials for cluster. It will not be remove from your kubeconfig.")
}
}
if dangerous {
err = kube.DeleteDangerous(clusterID)
} else {
err = kube.Delete(clusterID)
}
if err != nil {
return err
}
if kubeconfig != nil {
notice("Cluster deleted, removing credentials")
if err := removeFromKubeconfig(kubeconfig); err != nil {
warn("Cluster was deleted, but we couldn't remove it from your local kubeconfig. Try doing it manually.")
}
}
}
return nil