In this lesson, you will learn how to adhere to the principle of least privilege by mapping granular permissions directly to the identities of your running Pods.
The Role of ServiceAccounts
As you learned previously, a ServiceAccount provides an identity for processes running inside a Pod. By default, every Pod is assigned the default service account, which usually carries no permissions. To allow your application to interact with the Kubernetes API—such as listing ConfigMaps, watching custom resources, or updating status fields—you must grant the ServiceAccount specific permissions.
We achieve this by creating a Role (or ClusterRole) that defines what actions are allowed, and then using a RoleBinding to connect that Role to your specific ServiceAccount.
Connecting Permissions to Identities
Imagine you have an Operator component that needs to manage Secrets within its own namespace. Instead of giving the Pod wide-ranging access, you define a Role and link it to the ServiceAccount your Pod uses:
# 1. Define the permissions
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: secret-reader
rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "list"]
---
# 2. Bind the Role to the ServiceAccount
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-secrets-binding
subjects:
- kind: ServiceAccount
name: my-app-service-account
roleRef:
kind: Role
name: secret-reader
apiGroup: rbac.authorization.k8s.io
Finally, you must ensure your Pod manifest references the account by adding the serviceAccountName field:
spec:
serviceAccountName: my-app-service-account
containers:
- name: app
image: my-image:latest
Why this matters
By explicitly binding a Role to a ServiceAccount, you ensure that even if a container inside your Pod is compromised, the attacker is limited to the specific API verbs and resources you defined for that ServiceAccount. It prevents "permission creep," where pods accidentally inherit cluster-admin rights, making your cluster significantly more resilient and secure.
Key Takeaway: Always assign a dedicated ServiceAccount to your Pods and use RoleBindings to grant only the minimum set of permissions required for the application to function.