Skip to content

RBAC in Kubernetes

Role-Based Access Control (RBAC) is a security mechanism used in Kubernetes to regulate access to cluster resources.^[03.k8s集群.md] It operates by defining permissions (which can be performed on specific resources) and assigning them to subjects (users, groups, or service accounts).

In RBAC, operations are defined through a combination of: * Rules: Permissions that define what actions (verbs) are allowed. * Subjects: The entities (users, groups, or service accounts) that are granted the permissions. * Resources: The Kubernetes objects (e.g., pods, services, endpoints) that the rules apply to.

Core Components

Kubernetes RBAC is implemented using four primary object types.^[03.k8s集群.md]

Role and ClusterRole

A Role and a ClusterRole both contain sets of permissions (rules), but they differ in scope: * Role: Grants permissions within a specific namespace. * ClusterRole: Grants permissions cluster-wide (across all namespaces) or for non-namespaced resources (like nodes).

RoleBinding and ClusterRoleBinding

A Binding links a subject (user, group, or service account) to a Role or ClusterRole, effectively granting the defined permissions to that subject.^[03.k8s集群.md] * RoleBinding: Grants permissions defined in a Role (or ClusterRole) to subjects within a specific namespace. * ClusterRoleBinding: Grants permissions defined in a ClusterRole to subjects across the entire cluster.

Example Configuration

RBAC is typically configured using YAML manifests.^[03.k8s集群.md] Below is an example configuration for a system component (like CoreDNS) requiring specific privileges.

Service Account

First, a ServiceAccount acts as the identity for the application.

apiVersion: v1
kind: ServiceAccount
metadata:
  name: coredns
  namespace: kube-system
^[03.k8s集群.md]

ClusterRole

The ClusterRole defines what can be done. In this example, the system:coredns role allows listing and watching endpoints, services, pods, and namespaces.^[03.k8s集群.md]

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: system:coredns
rules:
- apiGroups:
  - ""
  resources:
  - endpoints
  - services
  - pods
  - namespaces
  verbs:
  - list
  - watch

ClusterRoleBinding

The ClusterRoleBinding connects the identity to the permissions.^[03.k8s集群.md]

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: system:coredns
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:coredns
subjects:
- kind: ServiceAccount
  name: coredns
  namespace: kube-system

Sources

^[03.k8s集群.md]