日期: 2021 年 9 月 18 日

用python实现helm template功能

背景

众所周知,helm template 包名 -f values.yaml >输出文件。这个方式能渲染go-template,自动填充{{ .Values.XXX }}参数到文件里。现在有一个需求,需要用python来实现类似的功能。那么就来看看我的最后实现吧


sapmle.tmpl 待填充文件

{{ .Values.Count }} items are made of {{ .Values.Material }}
{{ .Values.Material }} items are made of {{ .Values.Material }}
{{ .Values.Material }} items are made of {{ .Values.Count }}
{{ .Values.mqtt.server }} dadasdjsaijaid

values.yml 参数文件

Count: 14
Material: Wool
mqtt:
  server: 172.15.62.2

python 代码

import re

from ruamel import yaml


def traverse(dic, path=None):
    if not path:
        path = []
    if isinstance(dic, dict):
        for x in dic.keys():
            local_path = path[:]
            local_path.append(x)
            for b in traverse(dic[x], local_path):
                yield b
    else:
        yield path, dic


def template_render(source_file, values_file, dest_file):
    with open(source_file, 'r') as source:
        origin = source.read()

    with open(values_file, 'r', encoding='utf-8') as vaules:
        result = yaml.load_all(vaules.read(), Loader=yaml.Loader)
        yaml_dict = list(result)[0]
    for x in traverse(yaml_dict):
        match = "\{\{ \.Values." + '.'.join(x[0]) + " \}?\}"
        origin = re.sub(match, str(x[1]), origin)

    with open(dest_file, 'w+') as dest:
        dest.write(origin)


if __name__ == '__main__':
    template_render('sample.tmpl', "values.yml","result.yaml")

result.yaml 渲染结果

14 items are made of Wool
Wool items are made of Wool
Wool items are made of 14
172.15.62.2 dadasdjsaijaid

苏ICP备18047533号-1