I made a demo with kubernetes/go-client where i tried to list pods from my cluster.
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
fmt.Fprint(w, "There are d pods in the cluster\n", len(pods.Items))
I created serviceaccount token to assign to the pod where this code is running in.
But when code is executed pods.Items has no pods.
I deployed this pod inside minikube. When I launch some kubectl command for listing pods, this way I can get resources so it is no t permissions problems.
I wonder what is happening and how i can fix it.
Repository https://github.com/srpepperoni/inframanager.git
Image is pushed into: https://hub.docker.com/r/jaimeyh/inframanager
The endpoint I have problems with is this one :
mux.HandleFunc("/getPods", GetPodsFromNamespace)
You need to check if the err
on the last line is non-nil.
pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
OK, there is the problem. pods is forbidden: User "system:serviceaccount:mis-pruebas:sa-prueba-go" cannot list resource "pods" in API group "" at the cluster scope
As the error message indicates, the ServiceAccount does not have permission to list pods at cluster scope. You need to create Role and bind it to the ServiceAccount.
The article Using RBAC Authorization even has a role example for how to create such a role.