I'm new to kubernetes. I'm trying to list all the pods in a namespace from inside a pod/container via the javascript client.
import k8s = require('@kubernetes/client-node');
const kc = new k8s.KubeConfig();
kc.loadFromDefault();
const k8sApi = kc.makeApiClient(k8s.Core_v1Api);
k8sApi.listNamespacedPod('development')
.then((res) => {
console.log(res.body);
}).catch((err) => {
console.log(err);
});
The response error when I look at my pod logs:
{ kind: 'Status',
apiVersion: 'v1',
metadata: {},
status: 'Failure',
message:
'pods is forbidden: User "system:serviceaccount:default:default" cannot list pods in the namespace "development"',
reason: 'Forbidden',
details: { kind: 'pods' },
code: 403 } }
I believe I need to create a new User or add some permissions to a Role but I'm not sure where and how. Thanks
Regarding the error:
'pods is forbidden: User "system:serviceaccount:default:default" cannot list pods in the namespace "development"',
the default service account token is stored in the pod at the location:
root@nginx-64f497f8fd-jtvgf:/# ls /var/run/secrets/kubernetes.io/serviceaccount/
ca.crt namespace token
but the default service account dont have access to the cluster resources like the one you are trying to do, so you need to either create a new service account , role , and role binding , and then start the pod with that service account , or bind the default service account to a role with required permissions.
Kuberentes RBAC details
As @Robert Panzer suggested in Access Kubernetes API without kubectl, you can create a role and a rolebinding to enable listing of pods with:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: pod-reader
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "watch", "list"]
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: pod-reader
subjects:
- kind: ServiceAccount
name: default
namespace: default
roleRef:
kind: ClusterRole
name: pod-reader
apiGroup: rbac.authorization.k8s.io