Search code examples
kubernetespermissionsnamespaces

How to see logs in k8s from another namespace


My objetive is to see logs from pods belonging to other namespaces, in order to diagnose problems.

Here are the permissions I've configured:

apiVersion: v1
kind: ServiceAccount
metadata:
  name: default
  namespace: jenkins
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: listar-recursos
rules:
  - apiGroups: [""]
    resources: ["pods", "pods/log"]
    verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: asgina-lista-recursos
  namespace: jenkins
subjects:
  - kind: ServiceAccount
    name: default
    namespace: jenkins
roleRef:
  kind: ClusterRole
  name: listar-recursos
  apiGroup: rbac.authorization.k8s.io

Here is the result after running from a pod inside the jenkins namespace:

kubectl logs -l name=myapp -n anothernamespace
Error from server (Forbidden): pods is forbidden: 
User "system:serviceaccount:jenkins:default"
cannot list resource "pods" in API group "" 
in the namespace "anothernamespace"

Before asking, I've read carefully this article: https://kubernetes.io/docs/reference/access-authn-authz/rbac/


Solution

  • Based on the YAML config you provided, the key issue i see here is that you've set up a RoleBinding in the jenkins namespace which limits the scope of permissions granted to that specific namespace. However, in order to access resources like pods and their logs across different namespaces, you need to use a ClusterRoleBinding instead of a RoleBinding.

    A ClusterRoleBinding grants the permissions defined in the associated ClusterRole to users or groups across all namespaces.

    So first, I’ll suggest change your RoleBinding to a ClusterRoleBinding, i.e :

    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRoleBinding
    metadata:
      name: asgina-lista-recursos-global
    subjects:
      - kind: ServiceAccount
        name: default
        namespace: jenkins
    roleRef:
      kind: ClusterRole
      name: listar-recursos
      apiGroup: rbac.authorization.k8s.io
    

    This configuration binds the listar-recursos ClusterRole to the default ServiceAccount in the jenkins namespace, but the binding is effective across all namespaces due to the use of ClusterRoleBinding.

    Then go ahead with applying this updated configuration to your Kubernetes cluster.

    After applying the updated ClusterRoleBinding, test fetching logs from another namespace again, and you should be able to access logs across all namespaces.