<p>I created a mutating admission webhook in my Kubernetes cluster.
The api mutation webhook adds tolerations to a Deployment YAML.
However, it says an error <code>Internal error occurred: jsonpatch add operation does not apply: doc is missing path: "/spec/template/spec/tolerations/"</code></p>

<p>My Yaml Sample file:</p>

<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  namespace: webhook
  labels:
    app: nginx 
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  strategy:
    rollingUpdate:
      maxSurge: 100%
      maxUnavailable: 50%
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: "nginx:1.17"
          imagePullPolicy: Always
          ports:
            - containerPort: 80
              name: nginx
</code></pre>

<p>Python code:</p>

<pre><code>     mutations = []
     mutations.append({"op": "add", "path": "/spec/template/spec/tolerations/" + str(counter),
 "value": {key: t[key]}})
</code></pre>

<p>However, upon testing error appears as stated above.
Please help. :(</p>

<p>I don't see the whole file, therefore I cannot correct it.
But the problem is with your path, you are probably linking an array -- you have to specify an index. When you want to add an element to the end of an array, use <code>-1</code> like this: <code>spec/template/spec/containers/0/env/-1</code></p>
<hr />
<p>Have a look at this example</p>
<ul>
<li>shortened yaml file:</li>
</ul>
<pre><code>...
spec:
  template:
    spec:
      containers: # this is an array, there is 0 in the path 
        - name: somename
          image: someimage
          env: # another array, we are putting the element at the end, therefore index is -1
          - name: SOME_VALUE_0
            value: &quot;foo&quot;
          - name: SOME_VALUE_1
            value: &quot;bar&quot;
          # I want to add second env variable SOME_VALUE_2 here
...
</code></pre>
<ul>
<li><code>kustomization.yaml</code></li>
</ul>
<pre><code>apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
     - ../link/to/your/yaml
patchesJson6902:
     - target:
            ...
       patch: |-
            - op: &quot;add&quot;
              path: &quot;/spec/jobTemplate/spec/template/spec/containers/0/env/-1&quot;
              value: {name: &quot;SOME_VALUE_2&quot;, value: &quot;baz&quot;}
</code></pre>
