如何将竖线 (|) 添加到来自 Python 的 yaml 文件中

How do I add a pipe the vertical bar (|) into a yaml file from Python

我有一个任务。我需要编写 python 代码来为 kubernetes 生成一个 yaml 文件。到目前为止,我一直在使用 pyyaml,它工作正常。这是我生成的 yaml 文件:

apiVersion: v1
kind: ConfigMap
data:
  info: 
    name: hostname.com
    aio-max-nr: 262144
    cpu:
      cpuLogicalCores: 4
    memory:
      memTotal: 33567170560
    net.core.somaxconn: 1024
    ...

但是,当我尝试创建此 configMap 时,错误是信息需要 string() 而不是地图。所以我进行了一些探索,似乎解决这个问题的最简单方法是在信息之后添加一个管道,如下所示:

apiVersion: v1
kind: ConfigMap
data:
  info: | # this will translate everything in data into a string but still keep the format in yaml file for readability
    name: hostname.com
    aio-max-nr: 262144
    cpu:
      cpuLogicalCores: 4
    memory:
      memTotal: 33567170560
    net.core.somaxconn: 1024
    ...

这样我的configmap就创建成功了。我的挣扎是我不知道如何从 python 代码添加竖线。这里我是手动添加的,但是我想把这整个过程自动化。

我写的部分 python 代码是,假装数据是一个 dict():

content = dict()
content["apiVersion"] = "v1"
content["kind"] = "ConfigMap"
data = {...}
info = {"info": data}
content["data"] = info

# Get all contents ready. Now write into a yaml file
fileName = "out.yaml"
with open(fileName, 'w') as outfile:
    yaml.dump(content, outfile, default_flow_style=False)   

我在网上搜索了很多案例,但是none个案例符合我的需要。提前致谢。

管道使包含的值成为字符串。 YAML 不处理该字符串,即使它包含具有 YAML 语法的数据。因此,您需要提供一个字符串作为值。

由于字符串包含YAML语法中的数据,您可以通过在上一步中使用YAML处理包含的数据来创建字符串。要使 PyYAML 以文字块样式转储标量(即使用 |),您需要一个自定义表示器:

import yaml, sys
from yaml.resolver import BaseResolver

class AsLiteral(str):
  pass

def represent_literal(dumper, data):
  return dumper.represent_scalar(BaseResolver.DEFAULT_SCALAR_TAG,
      data, style="|")

yaml.add_representer(AsLiteral, represent_literal)

info = {
  "name": "hostname.com",
  "aio-max-nr": 262144,
  "cpu": {
    "cpuLogicalCores": 4
  }
}

info_str = AsLiteral(yaml.dump(info))

data = {
  "apiVersion": "v1",
  "kind": "ConfigMap",
  "data": {
    "info": info_str
  }
}

yaml.dump(data, sys.stdout)

通过将呈现的 YAML 数据放入类型 AsLiteral,将调用已注册的自定义表示程序,将所需的样式设置为 |