Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Add support to clusterctl for inserting workload kubeconfig into an existing kubeconfig file #11942

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions cmd/clusterctl/cmd/get_kubeconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ package cmd
import (
"context"
"fmt"
"os"

"github.com/pkg/errors"
"github.com/spf13/cobra"
"k8s.io/client-go/tools/clientcmd"

clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/cluster-api/cmd/clusterctl/client"
Expand All @@ -32,6 +34,7 @@ type getKubeconfigOptions struct {
kubeconfig string
kubeconfigContext string
namespace string
intoKubeconfig string
}

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

// completions
getKubeconfigCmd.ValidArgsFunction = resourceNameCompletionFunc(
Expand Down Expand Up @@ -98,6 +103,35 @@ func runGetKubeconfig(workloadClusterName string) error {
if err != nil {
return err
}
if gk.intoKubeconfig != "" {
return intoKubeconfig(gk.intoKubeconfig, out)
}

fmt.Println(out)
return nil
}

func intoKubeconfig(path, kubeconfig string) error {
kubeconfigFile, err := os.CreateTemp("", "kubeconfig")
if err != nil {
return err
}
defer os.Remove(kubeconfigFile.Name())

if _, err = kubeconfigFile.WriteString(kubeconfig); err != nil {
return err
}
if err = kubeconfigFile.Close(); err != nil {
return err
}

rules := &clientcmd.ClientConfigLoadingRules{
Precedence: []string{path, kubeconfigFile.Name()},
}
config, err := rules.Load()
if err != nil {
return err
}

return clientcmd.WriteToFile(*config, rules.Precedence[0])
}
Loading