Search code examples
kubernetesrolesk8s-serviceaccountk8s-cluster-role

How to configure a ClusterRole for namespaced resources


I want to allow a ServiceAccount in namespace A to access a resource in namespace B. To achieve this I connect the ServiceAccount to a ClusterRole via a ClusterRoleBinding. The documentation says I can "use a ClusterRole to [1.] define permissions on namespaced resources and be granted within individual namespace(s)"

But looking through the K8s documentation I can't find a way how to create a ClusterRole with namespaced resources. How can I achieve this?


Solution

  • I find both other answers a little confusing, hopefully this is clearer.

    You did the right thing in creating a ClusterRole, but you want to bind it using a namespaced RoleBinding, not a ClusterRoleBinding.

    Example using your examples. Notice how the RoleBinding is in the B namespace, giving A's ServiceAccount the permissions defined in the ClusterRole, but limited to the B namespace.

    ---
    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRole
    metadata:
      name: what-a-is-allowed-to-do-in-b
    rules:
    - apiGroups: [""]
      resources: ["pods", "deployments"] # etc
      verbs: ["get", "list", "create"]
    ---
    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: my-app
      namespace: namespace-a
    ---
    apiVersion: rbac.authorization.k8s.io/v1
    kind: RoleBinding
    metadata:
      name: what-a-is-allowed-to-do-in-b
      namespace: namespace-b
    roleRef:
      apiGroup: rbac.authorization.k8s.io
      kind: ClusterRole
      name: what-a-is-allowed-to-do-in-b
    subjects:
    - kind: ServiceAccount
      name: my-app
      namespace: namespace-a
    

    Notes: You have to use the ClusterRole because you can't get outside your own namespace without one. By using a RoleBinding, which is namespaced, you can then limit the access to the scope of the namespace of that RoleBinding.