52 lines
1.8 KiB
Python
52 lines
1.8 KiB
Python
# services/yaml_writer.py
|
|
from pathlib import Path
|
|
from typing import Dict, Any
|
|
from jinja2 import Environment, FileSystemLoader, select_autoescape
|
|
import shutil
|
|
|
|
ANSIBLE_ROOT = Path("ansible_workspace")
|
|
STAGING = ANSIBLE_ROOT / "staging"
|
|
TEMPLATE_DIR = Path("templates/ansible_templates")
|
|
STATIC_SEEDS = TEMPLATE_DIR / "_seeds" # optional: for csv/license seed files
|
|
|
|
env = Environment(
|
|
loader=FileSystemLoader(str(TEMPLATE_DIR)),
|
|
autoescape=select_autoescape(enabled_extensions=()),
|
|
trim_blocks=True,
|
|
lstrip_blocks=True,
|
|
)
|
|
|
|
def clean_dir(p: Path):
|
|
if p.exists():
|
|
for item in sorted(p.rglob("*"), reverse=True):
|
|
if item.is_file():
|
|
item.unlink()
|
|
elif item.is_dir():
|
|
item.rmdir()
|
|
|
|
def ensure_tree(scenario: str, hostname: str, esxi_host: str) -> Path:
|
|
"""
|
|
Returns the base path to .../staging/<scenario>/ and ensures the tree exists.
|
|
"""
|
|
base = STAGING / scenario
|
|
(base / "host_vars" / hostname).mkdir(parents=True, exist_ok=True)
|
|
(base / "host_vars" / esxi_host).mkdir(parents=True, exist_ok=True)
|
|
return base
|
|
|
|
def render_to_file(template_name: str, context: Dict[str, Any], out_path: Path):
|
|
print(f"[DEBUG] Rendering {out_path} with context: {context}")
|
|
tmpl = env.get_template(template_name)
|
|
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
out_path.write_text(tmpl.render(**context))
|
|
|
|
def copy_seed(name: str, dest: Path):
|
|
"""
|
|
Copies a static seed file (e.g., impus.csv, supis.csv, license_vars.yaml)
|
|
from templates/ansible_templates/_seeds/ if present; otherwise creates empty.
|
|
"""
|
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
seed = STATIC_SEEDS / name
|
|
if seed.exists():
|
|
shutil.copyfile(seed, dest)
|
|
else:
|
|
dest.write_text("") # empty default |