@@ -19,9 +19,11 @@ package cmd
1919import (
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 bool
3538}
3639
3740var 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 ().BoolVar (& gk .intoKubeconfig , "into-kubeconfig" , false ,
74+ "Inserts the workload cluster kubeconfig into the kubeconfig file." )
7075
7176 // completions
7277 getKubeconfigCmd .ValidArgsFunction = resourceNameCompletionFunc (
@@ -98,6 +103,34 @@ func runGetKubeconfig(workloadClusterName string) error {
98103 if err != nil {
99104 return err
100105 }
106+ if gk .intoKubeconfig {
107+ return intoKubeconfig (out )
108+ }
109+
101110 fmt .Println (out )
102111 return nil
103112}
113+
114+ func intoKubeconfig (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 .NewDefaultClientConfigLoadingRules ()
129+ rules .Precedence = append (rules .Precedence , kubeconfigFile .Name ())
130+ config , err := rules .Load ()
131+ if err != nil {
132+ return err
133+ }
134+
135+ return clientcmd .WriteToFile (* config , rules .Precedence [0 ])
136+ }
0 commit comments