如何解决如何在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 举报,一经查实,本站将立刻删除。