I have a secret in my kubernetes cluster which contains a kubeconfig of another Cluster. I want to be able to connect to that cluster in my Go code.
I only found ways to create a client via a kubeconfig FILE but not with a kubeconfig string.
This is my code so far:
// Read secret
kubeconfigSecret := &corev1.Secret{}
err := apiReader.Get(context.Background(), client.ObjectKey{Namespace: namespace, Name: name}, kubeconfigSecret)
if err != nil {
// error handling
}
kubeconfigBytes, ok := kubeconfigSecret.Data["kubeconfig"]
if !ok {
// error handling
}
kubeconfigString := string(kubeconfigBytes)
CodePudding user response:
There are several ways for this purpose, for example:
content := `a kubeconfig string`
tmpfile, err := os.CreateTemp("", "kubeconfig")
if err != nil {
...
}
defer os.Remove(tmpfile.Name())
if err := os.WriteFile(tmpfile.Name(), []byte(content), 0666); err != nil {
...
}
config, err := clientcmd.BuildConfigFromFlags("", tmpfile.Name())
if err != nil {
...
}
clientset,err := kubernetes.NewForConfig(config)
Another way is to use clientcmd.RESTConfigFromKubeConfig
:
content := `a kubeconfig string`
config, err := clientcmd.RESTConfigFromKubeConfig([]byte(content))
if err != nil {
...
}
clientset, err := kubernetes.NewForConfig(config)