Kustomize patch securityContext of all containers within deployments/staefulset

Asking for help? Comment out what you need so we can get more information to help you!

Cluster information:

Kubernetes version: 1.27.10
Cloud being used: bare-metal
Installation method: Rancher
Host OS: RHEL
CNI and version: Calico
CRI and version: Cri-o

You can format your yaml by highlighting it and pressing Ctrl-Shift-C, it will make your output easier to read.

First of all my background: I know Kubernetes really well but not kustomize.

My question is how to patch every container in all deployments/statefulsets via kustomize. Specially I want to update the securityContext of these with the following values:

"allowPrivilegeEscalation": false
capabilities:
        drop:
          - ALL

This is needed because our customer introduced this kind of security mechanism.
I want to install Kubeflow which has a lot of deployments and sts. (This is the reason I use Kustomize)

I use the latest Kustomize version.

Currently i tried it with json patch:

[
  {
    "op": "add",
    "path": "/spec/template/spec/containers/*/securityContext",
    "value": {
      "allowPrivilegeEscalation": false
    }
  }
]

and

[
  {
    "op": "add",
    "path": "/spec/template/spec/containers/*/securityContext/capabilities/drop",
    "value": ["ALL"]
  }
]

But this does not work.

Can someone help me?

PS: If something with this topic is wrong, please tell me. My first post.

Thanks to everyone who is willing to help me, I really appreciate all of you!

I tried doing the same thing for allowPrivilegeEscalation, found patch does not support wildcard, only containers/0/sec…, containers/1/sec…

replace does allow wild card, but that doesn’t meet the needs either as we’d need a valid source…

just had an idea, and tested it;

  1. patch pod 0
  2. replace all using that pod as source

it works…

main kustomize:

...
patches:
- path: security-patches/ks-explicitPrivilege.yaml
  target:
    kind: Deployment
replacements:
  - path: security-patches/replace-explicitPrivilege.yaml 

patch file for pod 0 in all deployment:

- op: replace
  path: /spec/template/spec/containers/0/securityContext/privileged
  value: false

replace file for ALL containers based off pod 0

---
source: 
  kind: Deployment
  name: **[YOUR_DEPLOYMENT_NAME]**
  fieldPath: spec.template.spec.containers.0.securityContext.privileged
targets:
- select:
    kind: Deployment
  fieldPaths: 
  - spec.template.spec.containers.*.securityContext.privileged
  options:
    create: true

only part not generic is;

  • YOUR_DEPLOYMENT_NAME

:warning: best practice would be to edit the base files instead of patch them, but the patch/replace is still useful.

We fixed it with a replacsement in json format

… containers/*/…

Your solution also works thanks :slight_smile: