How to create a kubernetes client in Go from a Kubeconfig String

huangapple go评论84阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2022年11月22日 19:14:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/74531736.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定