配置渲染工具
dockerfile
FROM python:3.11.3-alpine3.17
COPY requirements.txt .
RUN pip install --upgrade pip -i https://mirrors.cloud.tencent.com/pypi/simple && \
pip install --no-cache-dir -r requirements.txt -i https://mirrors.cloud.tencent.com/pypi/simple && \
rm -f requirements.txt
requirements.txt
Jinja2
MarkupSafe
PyYAML
jinja2-base64-filters
镜像构建
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, argparse
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__":
parser = argparse.ArgumentParser(description="Render script")
parser.add_argument("--input_dir", type=str, default="templates", help="Input directory")
parser.add_argument("--output_dir", type=str, default="deploy", help="Output directory")
parser.add_argument("--config_file", type=str, default="config.yaml", help="Config file")
args = parser.parse_args()
input_dir = args.input_dir
output_dir = args.output_dir
config_file = args.config_file
# 渲染并加载配置文件
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 \
config-render:v1.0 \
python render.py --input_dir=$1 --output_dir=$2 --config_file=$3