<p>I am trying to manipulate a kubernetes yaml file with python's pyyaml. I'm trying to add some annotations, but when I dump them the output is empty.</p>
<p>Add <code>key</code>,<code>val</code> in a <code>Deployment</code>:</p>
<pre class="lang-py prettyprint-override"><code>file_content = &quot;&quot;
try:
    with open(filename, &quot;r&quot;) as f:
        file_content = yaml.safe_load_all(f.read())
except:
    sys.exit(1)

for doc in file_content:
    if doc['kind'] == &quot;Deployment&quot;:
        metadata = doc['spec']['template']['metadata']

        if 'annotations' not in metadata.keys():
            metadata['annotations'] = {}
        
        metadata['annotations']['key'] = 'val'

yaml.safe_dump_all(documents=file_content, stream=sys.stdout)
</code></pre>
<p>I would like to obtain:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
...
spec:
  ...
  template:
    metadata:
    ...
      annotations:
        'key': 'val'
</code></pre>
<p>How can I do that?</p>
<blockquote>
<p>Note that in the output there's should be the single quote mark <code>'</code>.</p>
</blockquote>

sctx
<p>I found a solution. It seems that modifying the iterator returned by the <code>yaml.load</code> function results in an empty structure, so empty results.</p>
<p>I copy each element in the operator in a new structure and then apply edits to it.</p>
<p>The following works properly</p>
<pre class="lang-py prettyprint-override"><code>resources = []

for res in file_content:
    if res['kind'] == &quot;Deployment&quot;:

        # manipulate res
    resources.append(res)

yaml.safe_dump_all(documents=resources, stream=sys.stdout)
</code></pre>
