Enforce pod security standards
In this task you'll stop pods running as root in a namespace.
Pod Security Admission is built into Kubernetes. Label a namespace with an enforce level (privileged, baseline or restricted) and it refuses new pods that break it.
Restricted needs runAsNonRoot (with a non-zero user), allowPrivilegeEscalation false, all capabilities dropped and the RuntimeDefault seccomp profile. Existing pods aren't touched: restart them to check.
Example. After an audit, Fernhill Cloud enforces restricted in every app namespace; a deployment that still ran as root failed to roll out and the team fixed its image.
Costs money. This task creates resources that are charged while they exist. Delete them as soon as you finish.
Before you start
You need: An AKS cluster. Time: 20 minutes.
Where to look
- kubectl label namespace
- pod-security.kubernetes.io/enforce
Steps
- Check first:
kubectl label --dry-run=server --overwrite ns shop pod-security.kubernetes.io/enforce=restricted.It lists the pods that would break. - Fix the deployment's securityContext, then label the namespace for real.
kubectl rollout restart deploy/<name>and check the new pods start.
Commands
# Connect kubectl to the cluster first
az aks get-credentials -g <group> -n <cluster>
kubectl label --dry-run=server --overwrite ns shop pod-security.kubernetes.io/enforce=restricted
kubectl label --overwrite ns shop pod-security.kubernetes.io/enforce=restricted
Watch out for
- Cost
- Free.
- Security
- Use warn and audit labels first in busy namespaces, then enforce.
- Common mistakes
- Labelling first and then wondering why the next release fails, or forgetting that runAsNonRoot needs a non-root user ID.
Clean up
Remove the label with kubectl label ns shop pod-security.kubernetes.io/enforce-.
Words to know
- Pod Security Standards
- Three levels: privileged, baseline and restricted.
- securityContext
- Pod and container settings for user, privileges and capabilities.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands On