dockerfile
FROM python:3.11.3-alpine3.17
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt -i https://mirrors.cloud.tencent.com/pypi/simple && \
rm -f requirements.txt
requirements.txt
Jinja2==3.1.2
MarkupSafe==2.1.2
PyYAML==6.0
jinja2-base64-filters==0.1.4
镜像构建
docker build -t config-render:v1.0 .
docker save config-render:v1.0 -o config-render_v1.0.tar
render.py
#!/usr/bin/env python3
import os
from yaml import safe_load
from jinja2 import Environment, FileSystemLoader, Template
from jinja2_base64_filters import jinja2_base64_filters
def get_vars_from_file(config_file):
with open(config_file, 'r') as f:
vars_string = f.read()
base_vars = safe_load(vars_string)
context = Template(vars_string).render(base_vars)
# print(context)
return context
def render_template(input_path, output_path, context=None):
"""
渲染一个输入路径的文件或文件夹,并将渲染后的结果输出到指定输出路径
:param env: Jinja2的环境对象
:param input_path: 需要渲染的文件或文件夹路径
:param output_path: 渲染结果保存的输出路径
:param context: 传递给Jinja2模板的上下文数据
"""
# 如果输入路径是文件夹,则处理所有子文件和子目录
if os.path.isdir(input_path):
for dirpath, dirnames, filenames in os.walk(input_path):
# 创建相同的子目录结构
rel_dir = os.path.relpath(dirpath, input_path)
new_dir = os.path.join(output_path, rel_dir)
os.makedirs(new_dir, exist_ok=True)
# 处理所有的子文件
for filename in filenames:
input_file = os.path.join(dirpath, filename)
output_file = os.path.join(new_dir, filename)
render_template(input_file, output_file, context=context)
# 如果输入路径是一个文件,则对该文件进行渲染
else:
print("{} > {}".format(input_path, output_path))
env = Environment(extensions=["jinja2_base64_filters.Base64Filters"], loader=FileSystemLoader(os.path.dirname(input_path)))
template = env.get_template(os.path.basename(input_path))
rendered = template.render(context or {})
with open(output_path, "w", encoding="utf-8") as fp:
fp.write(rendered)
if __name__ == "__main__":
input_dir = "templates"
output_dir = "deploy"
config_file = "config.yaml"
# 渲染并加载配置文件
context = safe_load(get_vars_from_file(config_file))
# print(context)
render_template(input_dir, output_dir, context)
print("渲染完成!")
render.sh
#!/bin/bash
base_path=$(
cd "$(dirname "$0")" || exit 1
pwd
)
echo "开始渲染配置文件,请稍等..."
docker images | grep config-render > /dev/null 2>&1 || docker load -i ${base_path}/config-render_v1.0.tar
docker run -i --rm \
--name render \
--volume ${base_path}:/opt \
-w /opt \
harbor.stacs.cn/devops/config-render:v1.0 \
python render.py
标签:render,渲染,配置,context,input,path,工具,config,dir
From: https://www.cnblogs.com/xwjh/p/17757587.html