kubernetessecurity-contextpodsecuritypolicy

Why cant I configure POD-level securityContext settings to be applied to all underlying Containers?


In my POD, I wanted to restrict ALL my containers to read-only file systems with securityContext: readOnlyRootFilesystem: true
example (note: yaml reduced for brevity)

apiVersion: v1
kind: Pod
metadata:      
  labels:
    run: server123
  name: server123
spec:
  securityContext:
    readOnlyRootFilesystem: true
  containers:
  - image: server1-image
    name: server1 
  - image: server2-image
    name: server2
  - image: server3-image
    name: server3

this will result in:

error: error validating "server123.yaml": error validating data: ValidationError(Pod.spec.securityContext): unknown field "readOnlyRootFilesystem" in io.k8s.api.core.v1.PodSecurityContext; if you choose to ignore these errors, turn validation off with --validate=false

instead I have to configure as:

apiVersion: v1
    kind: Pod
    metadata:      
      labels:
        run: server123
      name: server123
    spec:
      containers:
      - image: server1-image
        name: server1
        securityContext:
          readOnlyRootFilesystem: true 
      - image: server2-image
        name: server2
        securityContext:
          readOnlyRootFilesystem: true
      - image: server3-image
        name: server3
        securityContext:
          readOnlyRootFilesystem: true

Is there a way to set this security restriction ONCE for all containers? If not why not?


Solution

  • In Kubernetes, can configure securityContext at pod and/or container level, containers would inherit pod-level settings, but can override in their own.

    The configuration options for pods and containers do not, however, overlap - you can only set specific ones at each level,
    Container level: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core
    Pod level: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core

    Its not documented clearly what can be inherited and what cannot (and why!). You have to read through both lists and compare. I would assume that POD's securityContext would allow, say, readOnlyRootFilesystem: true and various capabilities, to be set once and not have to be replicated in each underlying container's securityContext, but PodSecurityContext does not allow this!

    Would be particularly useful when (re)configuring various workloads to adhere to PodSecurityPolicies.

    I wonder why a Pod's securityContext configuration is labelled as such, and not instead as podSecurityContext, which is what it actually represents.