I want to add an initContainer to all of my pods (with a specific annotation) in my kustomize base. The newly added init container should be the first init container. My patch looks like this.
patches:
- target:
kind: Pod
annotationSelector: "database_init=True"
patch: |-
- op: add
path: /spec/initContainers/0
value:
name: database-init
...
This works fine for all pods that already have an init container. Unfortunately, I have pods without init containers and there the patch fails with the error add operation does not apply: doc is missing path: \"/spec/initContainers/0\"
.
How do I write a patch that works for all my pods?
Complete example:
.
├── base
│ ├── kustomization.yaml
│ ├── pod-1.yaml
│ └── pod-2.yaml
└── overlay
└── kustomization.yaml
# cat base/pod-1.yaml
apiVersion: v1
kind: Pod
metadata:
name: mypod-1
annotations:
database_init: True
spec:
initContainers:
- name: something
image: alpine:latest
command: ["sleep", "10" ]
containers:
- name: main
image: alpine:latest
command: [ "sleep", "60" ]
# cat base/pod-2.yaml
apiVersion: v1
kind: Pod
metadata:
name: mypod-2
annotations:
database_init: True
spec:
# initContainers:
# - name: something
# image: alpine:latest
# command: ["sleep", "10" ]
containers:
- name: main
image: alpine:latest
command: [ "sleep", "60" ]
# cat base/kustomization.yaml
resources:
- pod-1.yaml
- pod-2.yaml
# cat overlay/kustomization.yaml
resources:
- ../base
patches:
- target:
kind: Pod
annotationSelector: "database_init=True"
patch: |-
- op: add
path: /spec/initContainers/0
value:
name: database-init
image: alpine:latest
command: [ "sleep", 10 ]
Result:
$ kubectl kustomize overlay
error: add operation does not apply: doc is missing path: "/spec/initContainers/0": missing value
After uncommenting the init container of pod-2, everything works.
Edit: Added the annotationSelector.
Edit: Added the complete example code.