英文:
How to create a kubernetes client in Go from a Kubeconfig String
问题
我在我的Kubernetes集群中有一个包含另一个集群的kubeconfig的秘密。我希望能够在我的Go代码中连接到该集群。
我只找到了通过kubeconfig文件创建客户端的方法,而不是使用kubeconfig字符串。
这是我目前的代码:
// 读取秘密
kubeconfigSecret := &corev1.Secret{}
err := apiReader.Get(context.Background(), client.ObjectKey{Namespace: namespace, Name: name}, kubeconfigSecret)
if err != nil {
// 错误处理
}
kubeconfigBytes, ok := kubeconfigSecret.Data["kubeconfig"]
if !ok {
// 错误处理
}
kubeconfigString := string(kubeconfigBytes)
英文:
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)
答案1
得分: 1
有几种方法可以实现这个目的,例如:
content := `一个 kubeconfig 字符串`
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)
另一种方法是使用 clientcmd.RESTConfigFromKubeConfig
:
content := `一个 kubeconfig 字符串`
config, err := clientcmd.RESTConfigFromKubeConfig([]byte(content))
if err != nil {
...
}
clientset, err := kubernetes.NewForConfig(config)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论