<p>I am trying to add namespace to a multi document kubernetes yaml file if it doesn't exist but if the namespace field already exists don't update it using yq but i can't seem to get it to work. Is this possible?</p>
<p>e.g.</p>
<pre class="lang-yaml prettyprint-override"><code>---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: serviceaccount1
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: serviceaccount2
  namespace: namespace2
</code></pre>
<p>should end up something like this:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: ServiceAccount
metadata:
  name: serviceaccount1
  namespace: namespace1
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: serviceaccount2
  namespace: namespace2
</code></pre>
<p><strong>UPDATE:</strong></p>
<p>After successfully updating the yaml file thanks to:</p>
<p><a href="https://stackoverflow.com/a/74736018/16126608">https://stackoverflow.com/a/74736018/16126608</a></p>
<p>I am getting the namespace populated however due to the fact my yaml file was produced as an output of a helm template I am seeing the following issue where an empty document is having {} added as a result of the yq command, e.g.</p>
<pre class="lang-yaml prettyprint-override"><code>---
# Source: path/to/chart/templates/configmap.yaml
---
# Source: ppath/to/chart/templates/network-policy.yaml
---
</code></pre>
<p>Is coming out like this afterwards:</p>
<pre class="lang-yaml prettyprint-override"><code>---
# Source: path/to/chart/templates/configmap.yaml
---
{}
# Source: path/to/chart/templates/network-policy.yaml
---
{}
</code></pre>
<p>Is it possible to have yq to not add the {} and ignore the empty documents?</p>
<p>I am using mikefarah/yq</p>

gdix0n
<p>You can use <code>has</code> to check the existence of a field, and <code>not</code> to negate, then <code>select</code> it and add the new field.</p>
<p><a href="https://stackoverflow.com/tags/yq/info">Which implementation</a> of <code>yq</code> are you using?</p>
<p>Using <a href="https://github.com/kislyuk/yq" rel="nofollow noreferrer">kislyuk/yq</a>:</p>
<pre class="lang-bash prettyprint-override"><code>yq -y 'select(.metadata | has(&quot;namespace&quot;) | not).metadata.namespace = &quot;namespace1&quot;'
</code></pre>
<p>Using <a href="https://github.com/mikefarah/yq" rel="nofollow noreferrer">mikefarah/yq</a>:</p>
<pre class="lang-bash prettyprint-override"><code>yq 'select(.metadata | has(&quot;namespace&quot;) | not) |= .metadata.namespace = &quot;namespace1&quot;'
</code></pre>
