
How to Configure Pod Security Policies in Kubernetes
How to Configure Pod Security Policies in Kubernetes
In the world of Kubernetes, managing security at the pod level is crucial for maintaining a secure and stable environment. Pod Security Policies (PSPs) are a powerful way to control security-sensitive aspects of pod specifications, providing a method to enforce security and compliance standards within a Kubernetes cluster.
Prerequisites
- A working Kubernetes cluster (version 1.21 or higher recommended).
- Helm (Official site) and kubectl (Official site) installed on your local machine.
- Admin access to your Kubernetes cluster.
Step 1: Enable Pod Security Policies
First, ensure that your Kubernetes API server has the --enable-admission-plugins=PodSecurityPolicy
flag set. This enables the admission controller for Pod Security Policies.
kubectl edit deployment kube-apiserver -n kube-system
Look for the section where additional flags are added and include the PodSecurityPolicy
plugin.
Step 2: Create a Basic Pod Security Policy
Create a YAML file defining your Pod Security Policy settings. Here’s an example of a restricted PSP:
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
name: restricted
spec:
privileged: false
allowPrivilegeEscalation: false
runAsUser:
rule: "MustRunAsNonRoot"
seLinux:
rule: "RunAsAny"
supplementalGroups:
rule: "MustRunAs"
ranges:
- min: 1
max: 65535
volumes:
- 'configMap'
- 'downwardAPI'
- 'emptyDir'
- 'persistentVolumeClaim'
- 'projected'
- 'secret'
Step 3: Deploy the Pod Security Policy
Apply the policy to the cluster using kubectl
:
kubectl apply -f psp-restricted.yaml
Step 4: Bind the PSP to a Role
Next, we need to create a Role that allows the use of this PSP, and then bind it to a service account or user.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: psp-user
rules:
- apiGroups:
- policy
resourceNames:
- restricted
resources:
- podsecuritypolicies
verbs:
- use
kubectl create rolebinding psp-user-binding --role=psp-user --user= --namespace=
Troubleshooting
If you encounter issues where pods are failing to start due to PSP restrictions, consider relaxing some of the restrictions or creating PSPs with varied levels of permissions for different users/roles. Check the Kubernetes events and logs for error details.
Summary Checklist
- Ensure the Pod Security Policy plugin is enabled.
- Create and apply a Pod Security Policy file.
- Create a Role and bind it to users with the necessary access.
- Deploy and verify that your pods comply with the set PSPs.
- Troubleshoot using Kubernetes logs if issues arise.
For further assistance on Kubernetes configurations, consider reading our guide on how to monitor Kubernetes with Prometheus Operator.