Pyyaml:修改aws-auth-cm.yaml,保留多行字符串

2022-02-23 00:00:00 python pyyaml yaml

问题描述

我正在尝试用python加载一个YAML文件,对其进行修改并将其转储回来。 YAML如下所示:

data:
  mapRoles: |
    - username: system:node:{{EC2PrivateDNSName}}
      groups:
      - system:bootstrappers
      - system:nodes
kind: ConfigMap
metadata:
  name: aws-auth
  namespace: kube-system

我要修改它,以便输出文件在mapRoles:

中包含一个新行rolearn: awsarn
data:
  mapRoles: |
    - username: system:node:{{EC2PrivateDNSName}}
      groups:
        - system:bootstrappers
        - system:nodes
      rolearn: awsarn
kind: ConfigMap
metadata:
  name: aws-auth
  namespace: kube-system

但是我得到一个输出,其中mapRoles值像字符串一样被引用,并且包括文字

apiVersion: v1
data:
  mapRoles: "- username: system:node:{{EC2PrivateDNSName}}
  groups:
    - system:bootstrappers

        - system:nodes
  rolearn: arnaws"
kind: ConfigMap
metadata:
  name: aws-auth
  namespace: kube-system

我使用的代码:

with open ('/tmp/aws-auth-cm.yaml') as f:
  content = yaml.safe_load(f)
  content['data']['mapRoles'] = content['data']['mapRoles'] + '  rolearn: awsarn' 
with open("/tmp/aws-auth-cm.yaml", "w") as f:
  yaml.safe_dump(content, f, default_flow_style=False)

我还尝试使用yaml.safe_dump(content, f, default_flow_style=False, default_style='|'),然后所有值都有|-,键用双引号引起来:

"apiVersion": |-
  v1
"data":
  "mapRoles": |-
    - username: system:node:{{EC2PrivateDNSName}}
      groups:
        - system:bootstrappers
        - system:nodes
      rolearn: arnaws
"kind": |-
  ConfigMap
"metadata":
  "name": |

是否可以将style=‘|’仅应用于字符串,并确保键不带引号?

PyYAML

您可以尝试使用推荐答案执行此操作,但您需要加载挡路样式文字标量 (这就是|指示的这种多行构造的名称) 字符串子类,请确保可以修改它,然后在转储时使用特殊的表示符 对于再次转储为文字标量的子类。

完成此任务的简单方法是从PyYAML升级到 ruamel.yaml(免责声明:我是该包的作者),它不仅保留了 字面上的挡路,它还支持更新的YAML1.2规范(2009年发布), 保留注释和标记、整数和浮点格式,以及(可选)多余引号:

import sys
import ruamel.yaml


yaml = ruamel.yaml.YAML()
with open('aws-auth-cm.yaml') as f:
    content = yaml.load(f)
content['data']['mapRoles'] += '  rolearn: awsarn
'
with open('aws-auth-cm.yaml', 'w') as f:
    yaml.dump(content, f)

这提供了:

data:
  mapRoles: |
    - username: system:node:{{EC2PrivateDNSName}}
      groups:
      - system:bootstrappers
      - system:nodes
      rolearn: awsarn
kind: ConfigMap
metadata:
  name: aws-auth
  namespace: kube-system
请注意,我使用+=更改 从文字标量加载的"字符串"。并且我在 添加的字符串的末尾,因为否则文字标量将是 随着|-引入,-是挡路大嚼特嚼 运算符指示 剥离。

相关文章