<p>I have a k8s yaml file with below block</p>

<pre><code>spec:
  replicas: 1
  strategy:
    type: Recreate
</code></pre>

<p>and I want to add below block after "spec:"</p>

<pre><code>selector:
  matchLabels:
    app: test-app
</code></pre>

<p>The file is huge and has many "spec:" fields, so it should be added at the first match.</p>

<p>Final file content should look like this :</p>

<pre><code>spec:
  selector:
    matchLabels:
      app: test-app
  replicas: 1
  strategy:
    type: Recreate
</code></pre>

<p>I came up with this working solution using yq with correct indentation but it appends at the end of the file, Its painful to maintain and reading similar 100's of files.</p>

<pre><code>yq  -i -y '.spec += {selector:{matchLabels:{app:"test-app"}}}' filename.yaml
</code></pre>

<p>Any answers with tools like sed or awk are welcome.</p>

karthik101
<p>Here you go</p>

<pre><code>$ yq --yaml-output '.spec |= ({selector: {matchLabels: {app: "test-app"}}} + .)' &lt;/tmp/your-yaml-file.yaml 

spec:
  selector:
    matchLabels:
      app: test-app
  replicas: 1
  strategy:
    type: Recreate
</code></pre>

<p>Since you mentioned you have hundreds of files and each has many <code>spec</code> elements, it's unclear if this will solve your actual problem but hopefully it can be of help. Good luck!</p>
