Is there any way to pass to &genericclioptions
of k8s client a bytearray
of the kubeconfig?
https://pkg.go.dev/k8s.io/cli-runtime/pkg/genericclioptions
Currently, the genericclioptionsits
is taking it by default from the env/path to the file, but I need to pass it explicitly as bytearray
as a parameter and not a ref to a file or from the env, is there a way to do it?
I tried the following but it doesn’t work:
package main
import (
"bytes"
"github.com/spf13/pflag"
"k8s.io/cli-runtime/pkg/genericclioptions"
)
func main() {
kubeconfigData := []byte("my_kubeconfig")
// create a new flag set and bind the kubeconfig flag
flags := pflag.NewFlagSet("default", pflag.ExitOnError)
kubeconfigFlag := flags.String("kubeconfig", "", "absolute path to the kubeconfig file")
flags.Parse([]string{})
// set the kubeconfig flag to the data in the byte array
*kubeconfigFlag = "-"
configOverrides := &genericclioptions.ConfigOverrides{ClusterDefaults: genericclioptions.NewClusterDefaults()}
configLoader := genericclioptions.NewConfigFlags(false).WithOverrideFlags(configOverrides)
configLoader.KubeConfig = bytes.NewBuffer(kubeconfigData)
// ...
}
Any idea?
SECOND TRY
I tried also the following version and I got error: error loading config file , any idea?
func main() {
// read the kubeconfig file into a byte array
kubeconfig, err := ioutil.ReadFile("./kubeconfig--pln.yaml")
if err != nil {
panic(err)
}
// create a ConfigFlags object with the kubeconfig byte array
flags := genericclioptions.NewConfigFlags(false)
*flags.KubeConfig = string(kubeconfig)
dc, err := flags.ToDiscoveryClient()
if err != nil {
fmt.Println(err)
}
fmt.Println(dc)
res, err := dc.ServerPreferredNamespacedResources()
if err != nil {
fmt.Println(res)
}
// use the flags object to create a clientset or other Kubernetes API object
// ...
}
2
Answers
The code you posted is trying to set the kubeconfig flag to a string value of "-" instead of the byte array. To pass the kubeconfig as a byte array, you need to set the KubeConfig field of the ConfigLoader to a bytes.Buffer created from the byte array.
Here’s an updated version of the code:
Try the above code once, also u can follow these link1 Link2 Link3 Link4
Depending on how the config is used, one option might be to bypass the config loader step entirely.
For example: