Skip to content

Commit c43c52a

Browse files
committed
✨ Add support to clusterctl for inserting workload kubeconfig into an existing kubeconfig file
1 parent 3a8728f commit c43c52a

File tree

3 files changed

+182
-1
lines changed

3 files changed

+182
-1
lines changed

cmd/clusterctl/cmd/get_kubeconfig.go

+34
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@ package cmd
1919
import (
2020
"context"
2121
"fmt"
22+
"os"
2223

2324
"github.com/pkg/errors"
2425
"github.com/spf13/cobra"
26+
"k8s.io/client-go/tools/clientcmd"
2527

2628
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
2729
"sigs.k8s.io/cluster-api/cmd/clusterctl/client"
@@ -32,6 +34,7 @@ type getKubeconfigOptions struct {
3234
kubeconfig string
3335
kubeconfigContext string
3436
namespace string
37+
intoKubeconfig string
3538
}
3639

3740
var gk = &getKubeconfigOptions{}
@@ -67,6 +70,8 @@ func init() {
6770
"Path to the kubeconfig file to use for accessing the management cluster. If unspecified, default discovery rules apply.")
6871
getKubeconfigCmd.Flags().StringVar(&gk.kubeconfigContext, "kubeconfig-context", "",
6972
"Context to be used within the kubeconfig file. If empty, current context will be used.")
73+
getKubeconfigCmd.Flags().StringVar(&gk.intoKubeconfig, "into-kubeconfig", "",
74+
"Path to the kubeconfig file where the resulting kubeconfig will be inserted.")
7075

7176
// completions
7277
getKubeconfigCmd.ValidArgsFunction = resourceNameCompletionFunc(
@@ -98,6 +103,35 @@ func runGetKubeconfig(workloadClusterName string) error {
98103
if err != nil {
99104
return err
100105
}
106+
if gk.intoKubeconfig != "" {
107+
return intoKubeconfig(gk.intoKubeconfig, out)
108+
}
109+
101110
fmt.Println(out)
102111
return nil
103112
}
113+
114+
func intoKubeconfig(path, kubeconfig string) error {
115+
kubeconfigFile, err := os.CreateTemp("", "kubeconfig")
116+
if err != nil {
117+
return err
118+
}
119+
defer os.Remove(kubeconfigFile.Name())
120+
121+
if _, err = kubeconfigFile.WriteString(kubeconfig); err != nil {
122+
return err
123+
}
124+
if err = kubeconfigFile.Close(); err != nil {
125+
return err
126+
}
127+
128+
rules := &clientcmd.ClientConfigLoadingRules{
129+
Precedence: []string{path, kubeconfigFile.Name()},
130+
}
131+
config, err := rules.Load()
132+
if err != nil {
133+
return err
134+
}
135+
136+
return clientcmd.WriteToFile(*config, rules.Precedence[0])
137+
}

0 commit comments

Comments
 (0)