Kubernetes resources have quite a lot of lists in them and replacing an item in such lists is quite easy
using kustomize patches
with op: replace
.
Replacing a specific list item safely however is not as obvious as the order of items could change, leading to a technically valid but practically incorrect manifest.
Let’s take this deployment as an example:
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 2
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app
args:
- "--enable-feature x"
- "--auth-mode sso"
- "--threads 1"
image: my-app:1.0.0
ports:
- containerPort: 80
We might want to set --auth-mode local
instead, which can be done with a simple replace operation.
But if the order of items changes or a new one gets added before it we might instead overwrite another argument, leading to a disfunctional configuration.
We can safeguard against that by performing a op: test
beforehand, which will fail if the item is not what we expect.
- op: test
path: /spec/template/spec/containers/0/args/1
value: "--auth-mode sso"
- op: replace
path: /spec/template/spec/containers/0/args/1
value: "--auth-mode local"
Which leas to an error when the argument is not as expected:
$ kubectl kustomize .
error: testing value /spec/template/spec/containers/0/args/1 failed: test failed