更新Yaml文件,使用ruamel更新新字段

更新Yaml文件,使用ruamel更新新字段,yaml,pyyaml,ruamel.yaml,Yaml,Pyyaml,Ruamel.yaml,我正在尝试使用ruamelpython更新yaml文件 proc=subprocess.Popen(['kubectl','get','pod','web3','-o','yaml','--export'], stdout=subprocess.PIPE) rein=proc.stdout.read() result, indent, block_seq_indent = ruamel.yaml.util.load_yaml_guess_indent(rein, preserve_quotes=

我正在尝试使用ruamelpython更新yaml文件

proc=subprocess.Popen(['kubectl','get','pod','web3','-o','yaml','--export'], stdout=subprocess.PIPE)
rein=proc.stdout.read()
result, indent, block_seq_indent = ruamel.yaml.util.load_yaml_guess_indent(rein, preserve_quotes=True)
到目前为止,我已经尝试:

result['spec'].append('nodeSelector')
这会产生错误:

result['spec'].append('nodeSelector')
AttributeError: 'CommentedMap' object has no attribute 'append'
我也试过这样做:

result['spec']['nodeSelector']['kubernetes.io/hostname']='kubew1'
给出:

result['spec']['nodeSelector']['kubernetes.io/hostname']='kubew1'
File "/usr/local/lib/python3.6/dist-packages/ruamel/yaml/comments.py", line 752, in __getitem__
return ordereddict.__getitem__(self, key)
KeyError: 'nodeSelector'
我的初始Yaml文件是:

apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    app: demo
    name: web
  name: web3
  selfLink: /api/v1/namespaces/default/pods/web3
spec:
  containers:
  - image: aexlab/flask-sample-one
    imagePullPolicy: Always
    name: web
    ports:
    - containerPort: 5000
      name: http
      protocol: TCP
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-7bcc9
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
我想在“规范”中添加的预期字段是:

  nodeSelector:
    kubernetes.io/hostname: kubew1

任何关于如何使用ruamel库实现这一点的想法。

在YAML文件中,您的根级别集合是一个映射,映射中的键
spec
的值本身就是一个映射。使用
ruamel.yaml
named
CommentedMap
将这两个映射加载为类似
dict
的对象

与普通的
dict
s一样,您可以添加键-值对、删除键(及其值)和更新键的值,但没有与列表类似的
.append()
方法(即向列表中追加额外项)

您的输出有点简洁,但当然您不能只将
节点选择器添加到任何内容(列表/序列或dict/映射)中,并期望自动添加
kubernetes.io/hostname:kubew1
(映射本身)

您的尝试:

result['spec']['nodeSelector']['kubernetes.io/hostname'] = 'kubew1'
无法工作,因为没有dict
结果['spec']['nodeSelector']
可以添加密钥
kubernetes.io/hostname

您首先必须创建一个值为emtpy dict的键:

result['spec']['nodeSelector'] = {}
result['spec']['nodeSelector']['kubernetes.io/hostname'] = 'kubew1'
或者

请注意,上面的内容与
ruamel.yaml
无关,这只是基本的Python数据结构操作。还要注意的是,ruamel名称空间中有100多个库,其中
ruamel.yaml
只是作为开放源码发布的几个库之一,因此使用
ruamel
并不是一个非常明确的声明,当然上下文通常会提供有关您实际使用哪个库的足够信息

result['spec']['nodeSelector'] = {'kubernetes.io/hostname']: 'kubew1'}