如何在client-go中使用当前上下文以外的上下文访问多个集群?

问题描述

我按照 Kubernetes 文档使用 client-go 访问集群: https://kubernetes.io/docs/tasks/administer-cluster/access-cluster-api/#accessing-the-api-from-within-a-pod

现在,就我而言,在我的 kubeconfig 中,我有多个集群。它们的上下文名称是 cluster-1 和 cluster-2,cluster-1 是认集群。

package main

import (
  "context"
  "fmt"
  "k8s.io/apimachinery/pkg/apis/Meta/v1"
  "k8s.io/client-go/kubernetes"
  "k8s.io/client-go/tools/clientcmd"
)

func main() {
  // uses the current context in kubeconfig
  // path-to-kubeconfig -- for example,/root/.kube/config
  config,_ := clientcmd.BuildConfigFromFlags("","<path-to-kubeconfig>")
  // creates the clientset
  clientset,_ := kubernetes.NewForConfig(config)
  // access the API to list pods
  pods,_ := clientset.CoreV1().Pods("").List(context.Todo(),v1.ListOptions{})
  fmt.Printf("There are %d pods in the cluster\n",len(pods.Items))
}

以上代码认使用当前上下文。

我希望能够根据我的需要传递 cluster-1 或 cluster-2 作为上下文。

我该怎么做?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)