Scenario
Accidental deletions of critical Kubernetes deployments can cause downtime and impact application availability. To mitigate this risk, we can use Role-Based Access Control (RBAC) to restrict permissions.
Solution: Implementing RBAC to Restrict Delete Access
RBAC allows you to define fine-grained permissions for users and groups, preventing unauthorized actions like deleting deployments.
Step 1: Creating a Read-Only Role
This role grants read-only access to deployments within the production namespace.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: production
name: readonly-user
rules:
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get", "list"]
Step 2: Binding the Role to a User or Group
Bind the role to a specific user or group to enforce restricted permissions.
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
namespace: production
name: readonly-user-binding
subjects:
- kind: User
name: john.doe # Replace with the actual user
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: readonly-user
apiGroup: rbac.authorization.k8s.io
Step 3: Creating a Restricted Role for Developers
For users who need update access but not delete access, create a more restrictive role.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: production
name: restricted-dev
rules:
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get", "list", "update"]
Step 4: Enforcing Best Practices
- Use ClusterRoles if you need RBAC rules across multiple namespaces.
- Audit RBAC permissions regularly using tools like
kubectl auth can-i. - Implement Admission Controllers to prevent accidental deletions at the API level.
Alternative Approach: Using an Admission Controller
Kubernetes admission controllers can enforce policies that prevent deployment deletions. Example using Gatekeeper with Open Policy Agent (OPA):
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sDenyDelete
metadata:
name: deny-deployment-deletions
spec:
match:
kinds:
- apiGroups: ["apps"]
kinds: ["Deployment"]
Conclusion
By implementing RBAC and admission controllers, organizations can prevent accidental deletions, ensuring application stability and security in Kubernetes.