缺少测试用户的权限

我使用官方 golang kubernetes lib 支持的 watcherList 来获取有关 kubernetes 命名空间内创建、更新和删除服务的通知。这里是片段。


func (kc *KubernetesCollector) streamEvents(ctx context.Context) {

    kc.debugChannel <- fmt.Sprintf("Start streaming events from kubernetes API")


    watchList := cache.NewListWatchFromClient(kc.k8sClient.RESTClient(), "services", kc.k8sNamespace, fields.Everything())


    notificationCallbackToAddService := func(svc interface{}) {

        service := svc.(*v1.Service)

        kc.serviceNotificationChannel <- &serviceNotification{service, "add"}

    }


    notificationCallbackToDeleteService := func(svc interface{}) {

        service := svc.(*v1.Service)

        kc.serviceNotificationChannel <- &serviceNotification{service, "remove"}

    }


    callbacks := cache.ResourceEventHandlerFuncs{

        AddFunc:    notificationCallbackToAddService,

        DeleteFunc: notificationCallbackToDeleteService,

    }


    _, controller := cache.NewInformer(watchList, &v1.Service{}, time.Second*0, callbacks)

    go controller.Run(ctx.Done())

}

在我的测试中,我声明了kc.k8sClient在k8sAPI变量中定义的公共 api 地址。此外,我将承载令牌设置为针对集群进行身份验证并跳过验证不安全的 ssl 证书。


func TestK8sWatchList(t *testing.T) {

    require := require.New(t)

    ...

    k8sConfig, err := clientcmd.BuildConfigFromFlags(k8sAPI, "")

    require.NoError(err)


    k8sConfig.BearerToken = "<bearerToken>"

    k8sConfig.Transport = &http.Transport{

        TLSClientConfig: &tls.Config{

            InsecureSkipVerify: true,

        },

    }

    k8sClient, err := kubernetes.NewForConfig(k8sConfig)


    k8sCollector := NewK8sCollector(k8sClient, k8sNamespace)


    ...

}


我不明白为什么会收到错误消息,因为我认为服务帐户“t1k-test-serviceaccount”具有所有必需的权限。现在为测试用户定义了服务帐户、角色和角色绑定。



扬帆大鱼
浏览 173回答 2
2回答

神不在的星期二

您可以使用以下命令检查服务帐户的权限:kubectl&nbsp;auth&nbsp;can-i&nbsp;list&nbsp;services&nbsp;--namespace&nbsp;t1k&nbsp;--as=system:serviceaccount:t1k:t1k-test-serviceaccount您不需要手动设置令牌...您可以InClusterConfig像本示例中那样使用。Client-go 使用挂载在 Pod 内的服务帐户令牌,位于 /var/run/secrets/kubernetes.io/serviceaccount 路径时使用了 rest.InClusterConfig()。

慕森卡

我找到了解决方案。结构的k8sClientSet属性KubernetesCollector是一个指针。包的反射函数pkg/mod/k8s.io/client-go@v0.0.0-20200106225816-7985654fe8ee不能处理指针对象。type KubernetesCollector struct {&nbsp; &nbsp; ...&nbsp; &nbsp; k8sClient *kubernetes.ClientSet&nbsp; &nbsp; namespace string&nbsp; &nbsp; ...}CoreV1Interface我用from替换了 k8sClient k8s.io/client-go/kubernetes/typed/core/v1。因此,我更改了对 ListWatch 的调用。type KubernetesCollector struct {&nbsp; &nbsp;....&nbsp;&nbsp; &nbsp;iface&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;corev1.CoreV1Interface&nbsp; &nbsp;namespace&nbsp; &nbsp; &nbsp;string&nbsp; &nbsp;....}func (kc *KubernetesCollector) start(ctx context.Context) {&nbsp; &nbsp; watchList := cache.NewListWatchFromClient(kc.iface.RESTClient(), "services", kc.namespace, fields.Everything())&nbsp; &nbsp; ....}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go