Security & RBAC
Secure your cluster with Roles, RoleBindings, and ServiceAccounts.
Theory: RBAC Basics
Role-Based Access Control (RBAC) regulates access based on the roles of individual users within the cluster.
Key Concepts
- Role: Contains rules that represent a set of permissions (e.g., allow GET on pods). Scoped to a namespace.
- ClusterRole: Same as a Role, but scoped across the entire cluster.
- RoleBinding: Grants the permissions defined in a Role to a user, group, or ServiceAccount.
- ServiceAccount: Provides an identity for processes that run in a Pod.
apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: namespace: default name: pod-reader rules: - apiGroups: [""] resources: ["pods"] verbs: ["get", "watch", "list"]
Deep Dive: RBAC Authorization Flow
Role-Based Access Control connects Subjects (who) to Roles (what they can do). A RoleBinding is the glue that attaches the Role to the Subject within a specific Namespace.
3. Security Contexts
You can define privilege and access control settings for a Pod or Container. A best practice is
setting runAsNonRoot: true to prevent the container from running as the root user,
limiting the blast radius if the container escapes.
Hands-on Labs
Interview Prep: Security
NetworkPolicies are Kubernetes resources that let you configure how pods communicate with each other. They act like internal firewalls. By default, pods are non-isolated (they accept traffic from any source). A NetworkPolicy becomes active when it selects a pod, dropping all non-whitelisted traffic.
1) Implement RBAC with least-privilege Roles. 2) Implement NetworkPolicies to restrict intra-pod traffic. 3) Use SecurityContexts to drop capabilities and prevent running as root. 4) Enable audit logging. 5) Regularly scan container images for vulnerabilities.
While 'User Accounts' are for humans (administrators or developers), 'Service Accounts' are for processes running in Pods. If your application needs to talk to the Kubernetes API (e.g., a CI/CD runner scaling a deployment), you assign a ServiceAccount to the Pod.