Enforce Pod Security Standards with Namespace Labels

Namespaces can be labeled to enforce the Pod Security Standards.

Before you begin

Your Kubernetes server must be version v1.22. To check the version, enter kubectl version.

Requiring the baseline Pod Security Standard with namespace labels

This manifest defines a Namespace my-baseline-namespace that:

  • Blocks any pods that don’t satisfy the baseline policy requirements.
  • Generates a user-facing warning and adds an audit annotation to any created pod that does not meet the restricted policy requirements.
  • Pins the versions of the baseline and restricted policies to v1.22.
  1. apiVersion: v1
  2. kind: Namespace
  3. metadata:
  4. name: my-baseline-namespace
  5. labels:
  6. pod-security.kubernetes.io/enforce: baseline
  7. pod-security.kubernetes.io/enforce-version: v1.22
  8. # We are setting these to our _desired_ `enforce` level.
  9. pod-security.kubernetes.io/audit: restricted
  10. pod-security.kubernetes.io/audit-version: v1.22
  11. pod-security.kubernetes.io/warn: restricted
  12. pod-security.kubernetes.io/warn-version: v1.22

Add labels to existing namespaces with kubectl label

Note: When an enforce policy (or version) label is added or changed, the admission plugin will test each pod in the namespace against the new policy. Violations are returned to the user as warnings.

It is helpful to apply the --dry-run flag when initially evaluating security profile changes for namespaces. The Pod Security Standard checks will still be run in dry run mode, giving you information about how the new policy would treat existing pods, without actually updating a policy.

  1. kubectl label --dry-run=server --overwrite ns --all \
  2. pod-security.kubernetes.io/enforce=baseline

Applying to all namespaces

If you’re just getting started with the Pod Security Standards, a suitable first step would be to configure all namespaces with audit annotations for a stricter level such as baseline:

  1. kubectl label --overwrite ns --all \
  2. pod-security.kubernetes.io/audit=baseline \
  3. pod-security.kubernetes.io/warn=baseline

Note that this is not setting an enforce level, so that namespaces that haven’t been explicitly evaluated can be distinguished. You can list namespaces without an explicitly set enforce level using this command:

  1. kubectl get namespaces --selector='!pod-security.kubernetes.io/enforce'

Applying to a single namespace

You can update a specific namespace as well. This command adds the enforce=restricted policy to my-existing-namespace, pinning the restricted policy version to v1.22.

  1. kubectl label --overwrite ns my-existing-namespace \
  2. pod-security.kubernetes.io/enforce=restricted \
  3. pod-security.kubernetes.io/enforce-version=v1.22

Last modified July 26, 2021 at 4:34 PM PST : [PodSecurity] Correct and clarify a few things (6ac692be8)