<p>My Kustomize patching works to label the namespace but it overrides existing labels</p>
<p>Here's all the manifests -</p>
<p>kustomize.yaml</p>
<pre><code>apiVersion: kustomize.config.k8s.io/vlbetal
kind: Kustomization

resources:
 - ../../../../base/labels

patches:
 - path: patches/test-patch.yaml 
   target:
     kind: Namespace 
     name: dev-test
</code></pre>
<p>test-patch.yaml</p>
<pre><code>- op: add
  path: /metadata/labels 
  value:
    env: dev
    db: dev
</code></pre>
<p>namespace.yaml</p>
<pre><code>api Version: v1 
kind: Namespace 
metadata:
  name: dev-test
</code></pre>
<p>How do I avoid overriding existing namespace labels ?</p>

megha
<p>The current patch replaces the <code>labels</code> object with the given value, thus overriding all previous labels.</p>
<p>On a technical level, we want to add the two fields <code>env</code> and <code>db</code> to the <code>label</code>-object. Thus, we need two separate <code>add</code> operations to add the two fields:</p>
<pre><code>- op: add
  path: /metadata/labels/env
  value: dev
- op: add
  path: /metadata/labels/db
  value: dev
</code></pre>
<p>Note that in order for this solution to work, the namespace needs to have a <code>labels</code> object already. If it does not, <code>kustomize</code> will report the following error:</p>
<pre><code>Error: add operation does not apply: doc is missing path: &quot;/metadata/labels/env&quot;: missing value
</code></pre>
<p>We can add an empty <code>labels</code>-section like this:</p>
<pre><code>api Version: v1 
kind: Namespace 
metadata:
  name: dev-test
  labels: {}
</code></pre>
<p>If the namespace already has labels, e.g.:</p>
<pre><code>api Version: v1 
kind: Namespace 
metadata:
  name: dev-test
  labels:
    foo: bar
</code></pre>
<p>Then we need to do nothing; the new labels will be added.</p>
